Skip to content

[TwigBridge][Validator] Add the Twig constraint and its validator #58805

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Bridge/Twig/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Add `is_granted_for_user()` Twig function
* Add `field_id()` Twig form helper function
* Add a `Twig` constraint that validates Twig templates

7.2
---
Expand Down
56 changes: 56 additions & 0 deletions src/Symfony/Bridge/Twig/Tests/Validator/Constraints/TwigTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Tests\Validator\Constraints;

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Twig\Validator\Constraints\Twig;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

/**
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
class TwigTest extends TestCase
{
public function testAttributes()
{
$metadata = new ClassMetadata(TwigDummy::class);
$loader = new AttributeLoader();
self::assertTrue($loader->loadClassMetadata($metadata));

[$bConstraint] = $metadata->properties['b']->getConstraints();
self::assertSame('myMessage', $bConstraint->message);
self::assertSame(['Default', 'TwigDummy'], $bConstraint->groups);

[$cConstraint] = $metadata->properties['c']->getConstraints();
self::assertSame(['my_group'], $cConstraint->groups);
self::assertSame('some attached data', $cConstraint->payload);

[$dConstraint] = $metadata->properties['d']->getConstraints();
self::assertFalse($dConstraint->skipDeprecations);
}
}

class TwigDummy
{
#[Twig]
private $a;

#[Twig(message: 'myMessage')]
private $b;

#[Twig(groups: ['my_group'], payload: 'some attached data')]
private $c;

#[Twig(skipDeprecations: false)]
private $d;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Tests\Validator\Constraints;

use Symfony\Bridge\Twig\Validator\Constraints\Twig;
use Symfony\Bridge\Twig\Validator\Constraints\TwigValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
use Twig\DeprecatedCallableInfo;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
use Twig\TwigFilter;

/**
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
class TwigValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator(): TwigValidator
{
$environment = new Environment(new ArrayLoader());
$environment->addFilter(new TwigFilter('humanize_filter', fn ($v) => $v));
if (class_exists(DeprecatedCallableInfo::class)) {
$options = ['deprecation_info' => new DeprecatedCallableInfo('foo/bar', '1.1')];
} else {
$options = ['deprecated' => true];
}

$environment->addFilter(new TwigFilter('deprecated_filter', fn ($v) => $v, $options));

return new TwigValidator($environment);
}

/**
* @dataProvider getValidValues
*/
public function testTwigIsValid($value)
{
$this->validator->validate($value, new Twig());

$this->assertNoViolation();
}

/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value, $message, $line)
{
$constraint = new Twig('myMessageTest');

$this->validator->validate($value, $constraint);

$this->buildViolation('myMessageTest')
->setParameter('{{ error }}', $message)
->setParameter('{{ line }}', $line)
->setCode(Twig::INVALID_TWIG_ERROR)
->assertRaised();
}

/**
* When deprecations are skipped by the validator, the testsuite reporter will catch them so we need to mark the test as legacy.
*
* @group legacy
*/
public function testTwigWithSkipDeprecation()
{
$constraint = new Twig(skipDeprecations: true);

$this->validator->validate('{{ name|deprecated_filter }}', $constraint);

$this->assertNoViolation();
}

public function testTwigWithoutSkipDeprecation()
{
$constraint = new Twig(skipDeprecations: false);

$this->validator->validate('{{ name|deprecated_filter }}', $constraint);

$line = 1;
$error = 'Twig Filter "deprecated_filter" is deprecated in at line 1 at line 1.';
if (class_exists(DeprecatedCallableInfo::class)) {
$line = 0;
$error = 'Since foo/bar 1.1: Twig Filter "deprecated_filter" is deprecated.';
}
$this->buildViolation($constraint->message)
->setParameter('{{ error }}', $error)
->setParameter('{{ line }}', $line)
->setCode(Twig::INVALID_TWIG_ERROR)
->assertRaised();
}

public static function getValidValues()
{
return [
['Hello {{ name }}'],
['{% if condition %}Yes{% else %}No{% endif %}'],
['{# Comment #}'],
['Hello {{ "world"|upper }}'],
['{% for i in 1..3 %}Item {{ i }}{% endfor %}'],
['{{ name|humanize_filter }}'],
];
}

public static function getInvalidValues()
{
return [
// Invalid syntax example (missing end tag)
['{% if condition %}Oops', 'Unexpected end of template at line 1.', 1],
// Another syntax error example (unclosed variable)
['Hello {{ name', 'Unexpected token "end of template" ("end of print statement" expected) at line 1.', 1],
// Unknown filter error
['Hello {{ name|unknown_filter }}', 'Unknown "unknown_filter" filter at line 1.', 1],
// Invalid variable syntax
['Hello {{ .name }}', 'Unexpected token "punctuation" of value "." at line 1.', 1],
];
}
}
38 changes: 38 additions & 0 deletions src/Symfony/Bridge/Twig/Validator/Constraints/Twig.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Validator\Constraints;

use Symfony\Component\Validator\Attribute\HasNamedArguments;
use Symfony\Component\Validator\Constraint;

/**
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Twig extends Constraint
{
public const INVALID_TWIG_ERROR = 'e7fc55d5-e586-4cc1-924e-d27ee7fcd1b5';

protected const ERROR_NAMES = [
self::INVALID_TWIG_ERROR => 'INVALID_TWIG_ERROR',
];

#[HasNamedArguments]
public function __construct(
public string $message = 'This value is not a valid Twig template.',
public bool $skipDeprecations = true,
?array $groups = null,
mixed $payload = null,
) {
parent::__construct(null, $groups, $payload);
}
}
81 changes: 81 additions & 0 deletions src/Symfony/Bridge/Twig/Validator/Constraints/TwigValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
use Twig\Environment;
use Twig\Error\Error;
use Twig\Loader\ArrayLoader;
use Twig\Source;

/**
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
class TwigValidator extends ConstraintValidator
{
public function __construct(private Environment $twig)
{
}

public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof Twig) {
throw new UnexpectedTypeException($constraint, Twig::class);
}

if (null === $value || '' === $value) {
return;
}

if (!\is_scalar($value) && !$value instanceof \Stringable) {
throw new UnexpectedValueException($value, 'string');
}

$value = (string) $value;

if (!$constraint->skipDeprecations) {
$prevErrorHandler = set_error_handler(static function ($level, $message, $file, $line) use (&$prevErrorHandler) {

Check failure on line 49 in src/Symfony/Bridge/Twig/Validator/Constraints/TwigValidator.php

View workflow job for this annotation

GitHub Actions / Psalm

UndefinedVariable

src/Symfony/Bridge/Twig/Validator/Constraints/TwigValidator.php:49:106: UndefinedVariable: Cannot find referenced variable $prevErrorHandler (see https://psalm.dev/024)

Check failure on line 49 in src/Symfony/Bridge/Twig/Validator/Constraints/TwigValidator.php

View workflow job for this annotation

GitHub Actions / Psalm

UndefinedVariable

src/Symfony/Bridge/Twig/Validator/Constraints/TwigValidator.php:49:106: UndefinedVariable: Cannot find referenced variable $prevErrorHandler (see https://psalm.dev/024)
if (\E_USER_DEPRECATED !== $level) {
return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
}

$templateLine = 0;
if (preg_match('/ at line (\d+)[ .]/', $message, $matches)) {
$templateLine = $matches[1];
}

throw new Error($message, $templateLine);
});
}

$realLoader = $this->twig->getLoader();
try {
$temporaryLoader = new ArrayLoader([$value]);
$this->twig->setLoader($temporaryLoader);
$this->twig->parse($this->twig->tokenize(new Source($value, '')));
} catch (Error $e) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ error }}', $e->getMessage())
->setParameter('{{ line }}', $e->getTemplateLine())
->setCode(Twig::INVALID_TWIG_ERROR)
->addViolation();
} finally {
$this->twig->setLoader($realLoader);
if (!$constraint->skipDeprecations) {
restore_error_handler();
}
}
}
}
1 change: 1 addition & 0 deletions src/Symfony/Bridge/Twig/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"symfony/property-info": "^6.4|^7.0",
"symfony/routing": "^6.4|^7.0",
"symfony/translation": "^6.4|^7.0",
"symfony/validator": "^6.4|^7.0",
"symfony/yaml": "^6.4|^7.0",
"symfony/security-acl": "^2.8|^3.0",
"symfony/security-core": "^6.4|^7.0",
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/TwigBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Enable `#[AsTwigFilter]`, `#[AsTwigFunction]` and `#[AsTwigTest]` attributes
to configure extensions on runtime classes
* Add support for a `twig` validator

7.1
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Translation\LocaleSwitcher;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Validator\Constraint;
use Symfony\Contracts\Service\ResetInterface;
use Twig\Attribute\AsTwigFilter;
use Twig\Attribute\AsTwigFunction;
Expand Down Expand Up @@ -69,6 +70,10 @@ public function load(array $configs, ContainerBuilder $container): void
$container->removeDefinition('twig.translation.extractor');
}

if ($container::willBeAvailable('symfony/validator', Constraint::class, ['symfony/twig-bundle'])) {
$loader->load('validator.php');
}

foreach ($configs as $key => $config) {
if (isset($config['globals'])) {
foreach ($config['globals'] as $name => $value) {
Expand Down
22 changes: 22 additions & 0 deletions src/Symfony/Bundle/TwigBundle/Resources/config/validator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Bridge\Twig\Validator\Constraints\TwigValidator;

return static function (ContainerConfigurator $container) {
$container->services()
->set('twig.validator', TwigValidator::class)
->args([service('twig')])
->tag('validator.constraint_validator')
;
};
Loading