-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
56 changes: 56 additions & 0 deletions
56
src/Symfony/Bridge/Twig/Tests/Validator/Constraints/TwigTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
126 changes: 126 additions & 0 deletions
126
src/Symfony/Bridge/Twig/Tests/Validator/Constraints/TwigValidatorTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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], | ||
]; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
81
src/Symfony/Bridge/Twig/Validator/Constraints/TwigValidator.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
|
||
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(); | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22 changes: 22 additions & 0 deletions
22
src/Symfony/Bundle/TwigBundle/Resources/config/validator.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | ||
; | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.