Fix support for ignoring syntax erros in an undefined handler in guard

This commit is contained in:
Christophe Coevoet
2025-02-09 14:48:10 +01:00
parent 40a2d5b57f
commit 3794efe662
3 changed files with 70 additions and 2 deletions
+21 -2
View File
@@ -799,7 +799,17 @@ class ExpressionParser
private function getFunction(string $name, int $line): TwigFunction
{
if (!$function = $this->env->getFunction($name)) {
try {
$function = $this->env->getFunction($name);
} catch (SyntaxError $e) {
if (!$this->parser->shouldIgnoreUnknownTwigCallables()) {
throw $e;
}
$function = null;
}
if (!$function) {
if ($this->parser->shouldIgnoreUnknownTwigCallables()) {
return new TwigFunction($name, fn () => '');
}
@@ -819,7 +829,16 @@ class ExpressionParser
private function getFilter(string $name, int $line): TwigFilter
{
if (!$filter = $this->env->getFilter($name)) {
try {
$filter = $this->env->getFilter($name);
} catch (SyntaxError $e) {
if (!$this->parser->shouldIgnoreUnknownTwigCallables()) {
throw $e;
}
$filter = null;
}
if (!$filter) {
if ($this->parser->shouldIgnoreUnknownTwigCallables()) {
return new TwigFilter($name, fn () => '');
}
@@ -0,0 +1,22 @@
--TEST--
"guard" creates a compilation time condition on Twig callables availability
--TEMPLATE--
{% guard filter throwing_undefined_filter %}
NEVER
{{ 'a'|throwing_undefined_filter }}
{% else -%}
The throwing_undefined_filter filter doesn't exist
{% endguard %}
{% guard function throwing_undefined_function -%}
NEVER
{{ throwing_undefined_function() }}
{% else -%}
The throwing_undefined_function function doesn't exist
{% endguard %}
--DATA--
return []
--EXPECT--
The throwing_undefined_filter filter doesn't exist
The throwing_undefined_function function doesn't exist
+27
View File
@@ -12,6 +12,7 @@ namespace Twig\Tests;
*/
use Twig\DeprecatedCallableInfo;
use Twig\Error\SyntaxError;
use Twig\Extension\AbstractExtension;
use Twig\Extension\DebugExtension;
use Twig\Extension\SandboxExtension;
@@ -49,6 +50,32 @@ class IntegrationTest extends IntegrationTestCase
];
}
protected function getUndefinedFunctionCallbacks(): array
{
return [
static function (string $name) {
if ('throwing_undefined_function' === $name) {
throw new SyntaxError('This function is undefined in the tests.');
}
return false;
},
];
}
protected function getUndefinedTokenParserCallbacks(): array
{
return [
static function (string $name) {
if ('throwing_undefined_filter' === $name) {
throw new SyntaxError('This filter is undefined in the tests.');
}
return false;
},
];
}
protected static function getFixturesDirectory(): string
{
return __DIR__.'/Fixtures/';