Skip to content

Commit

Permalink
bug #4511 Ignore exceptions from undefined handlers when using the gu…
Browse files Browse the repository at this point in the history
…ard tag (fabpot)

This PR was merged into the 3.x branch.

Discussion
----------

Ignore exceptions from undefined handlers when using the guard tag

Fixes #4505

Commits
-------

b53c639 Ignore exceptions from undefined handlers when using the guard tag
  • Loading branch information
fabpot committed Dec 20, 2024
2 parents 91e6096 + b53c639 commit c1f7277
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# 3.18.0 (2024-XX-XX)

* Ignore `SyntaxError` exceptions from undefined handlers when using the `guard` tag
* Add a way to stream template rendering (`TemplateWrapper::stream()` and `TemplateWrapper::streamBlock()` )

# 3.17.1 (2024-12-12)
Expand Down
6 changes: 5 additions & 1 deletion src/TokenParser/GuardTokenParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ public function parse(Token $token): Node

$nameToken = $stream->expect(Token::NAME_TYPE);

$exists = null !== $this->parser->getEnvironment()->$method($nameToken->getValue());
try {
$exists = null !== $this->parser->getEnvironment()->$method($nameToken->getValue());
} catch (SyntaxError) {
$exists = false;
}

$stream->expect(Token::BLOCK_END_TYPE);
if ($exists) {
Expand Down
22 changes: 22 additions & 0 deletions tests/TokenParser/GuardTokenParserTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Twig\Tests\TokenParser;

use PHPUnit\Framework\TestCase;
use Twig\Environment;
use Twig\Error\SyntaxError;
use Twig\Loader\ArrayLoader;
use Twig\Parser;
use Twig\Source;

class GuardTokenParserTest extends TestCase
{
public function testUndefinedHandlers()
{
$this->expectNotToPerformAssertions();

$env = new Environment(new ArrayLoader(), ['cache' => false, 'autoescape' => false]);
$env->registerUndefinedFunctionCallback(fn ($name) => throw new SyntaxError('boom.'));
(new Parser($env))->parse($env->tokenize(new Source('{% guard function boom %}{% endguard %}', '')));
}
}

0 comments on commit c1f7277

Please sign in to comment.