Skip to content

Commit

Permalink
feature #35849 [ExpressionLanguage] Added expression language syntax …
Browse files Browse the repository at this point in the history
…validator (Andrej-in-ua)

This PR was squashed before being merged into the 5.1-dev branch.

Discussion
----------

[ExpressionLanguage] Added expression language syntax validator

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       | #35700
| License       | MIT
| Doc PR        | N/A <!-- required for new features -->

Proposal implementation #35700

The current solution is a compromise between support complexity and cleanliness.

I tried different solutions to the issue. A beautiful solution was obtained only with full duplication of the parser code. That is unacceptable because parser complexity is quite high.

The main problem in this solution is that nodes instances are created which are then not used. I do not think that linter can be a bottleneck and will greatly affect performance. If this is corrected, the parser code becomes a bunch of if's.

JFI: I did not added parsing without variable names, because this breaks caching and potential location for vulnerabilities.

Commits
-------

a5cd965494 [ExpressionLanguage] Added expression language syntax validator
  • Loading branch information
fabpot committed May 5, 2020
2 parents 77aed83 + 2cbde2e commit 0d001e7
Show file tree
Hide file tree
Showing 5 changed files with 189 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ CHANGELOG
* allow to define a reusable set of constraints by extending the `Compound` constraint
* added `Sequentially` constraint, to sequentially validate a set of constraints (any violation raised will prevent further validation of the nested constraints)
* added the `divisibleBy` option to the `Count` constraint
* added the `ExpressionLanguageSyntax` constraint

5.0.0
-----
Expand Down
42 changes: 42 additions & 0 deletions Constraints/ExpressionLanguageSyntax.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

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

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*
* @author Andrey Sevastianov <[email protected]>
*/
class ExpressionLanguageSyntax extends Constraint
{
const EXPRESSION_LANGUAGE_SYNTAX_ERROR = '1766a3f3-ff03-40eb-b053-ab7aa23d988a';

protected static $errorNames = [
self::EXPRESSION_LANGUAGE_SYNTAX_ERROR => 'EXPRESSION_LANGUAGE_SYNTAX_ERROR',
];

public $message = 'This value should be a valid expression.';
public $service;
public $validateNames = true;
public $names = [];

/**
* {@inheritdoc}
*/
public function validatedBy()
{
return $this->service;
}
}
55 changes: 55 additions & 0 deletions Constraints/ExpressionLanguageSyntaxValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

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

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\SyntaxError;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
* @author Andrey Sevastianov <[email protected]>
*/
class ExpressionLanguageSyntaxValidator extends ConstraintValidator
{
private $expressionLanguage;

public function __construct(ExpressionLanguage $expressionLanguage)
{
$this->expressionLanguage = $expressionLanguage;
}

/**
* {@inheritdoc}
*/
public function validate($expression, Constraint $constraint): void
{
if (!$constraint instanceof ExpressionLanguageSyntax) {
throw new UnexpectedTypeException($constraint, ExpressionLanguageSyntax::class);
}

if (!\is_string($expression)) {
throw new UnexpectedTypeException($expression, 'string');
}

try {
$this->expressionLanguage->lint($expression, ($constraint->validateNames ? ($constraint->names ?? []) : null));
} catch (SyntaxError $exception) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ syntax_error }}', $this->formatValue($exception->getMessage()))
->setInvalidValue((string) $expression)
->setCode(ExpressionLanguageSyntax::EXPRESSION_LANGUAGE_SYNTAX_ERROR)
->addViolation();
}
}
}
88 changes: 88 additions & 0 deletions Tests/Constraints/ExpressionLanguageSyntaxTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

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

namespace Symfony\Component\Validator\Tests\Constraints;

use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\SyntaxError;
use Symfony\Component\Validator\Constraints\ExpressionLanguageSyntax;
use Symfony\Component\Validator\Constraints\ExpressionLanguageSyntaxValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

class ExpressionLanguageSyntaxTest extends ConstraintValidatorTestCase
{
/**
* @var \PHPUnit\Framework\MockObject\MockObject|ExpressionLanguage
*/
protected $expressionLanguage;

protected function createValidator()
{
return new ExpressionLanguageSyntaxValidator($this->expressionLanguage);
}

protected function setUp(): void
{
$this->expressionLanguage = $this->createExpressionLanguage();

parent::setUp();
}

public function testExpressionValid(): void
{
$this->expressionLanguage->expects($this->once())
->method('lint')
->with($this->value, []);

$this->validator->validate($this->value, new ExpressionLanguageSyntax([
'message' => 'myMessage',
]));

$this->assertNoViolation();
}

public function testExpressionWithoutNames(): void
{
$this->expressionLanguage->expects($this->once())
->method('lint')
->with($this->value, null);

$this->validator->validate($this->value, new ExpressionLanguageSyntax([
'message' => 'myMessage',
'validateNames' => false,
]));

$this->assertNoViolation();
}

public function testExpressionIsNotValid(): void
{
$this->expressionLanguage->expects($this->once())
->method('lint')
->with($this->value, [])
->willThrowException(new SyntaxError('Test exception', 42));

$this->validator->validate($this->value, new ExpressionLanguageSyntax([
'message' => 'myMessage',
]));

$this->buildViolation('myMessage')
->setParameter('{{ syntax_error }}', '"Test exception around position 42."')
->setCode(ExpressionLanguageSyntax::EXPRESSION_LANGUAGE_SYNTAX_ERROR)
->assertRaised();
}

protected function createExpressionLanguage(): MockObject
{
return $this->getMockBuilder('\Symfony\Component\ExpressionLanguage\ExpressionLanguage')->getMock();
}
}
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"symfony/yaml": "^4.4|^5.0",
"symfony/config": "^4.4|^5.0",
"symfony/dependency-injection": "^4.4|^5.0",
"symfony/expression-language": "^4.4|^5.0",
"symfony/expression-language": "^5.1",
"symfony/cache": "^4.4|^5.0",
"symfony/mime": "^4.4|^5.0",
"symfony/property-access": "^4.4|^5.0",
Expand All @@ -44,6 +44,7 @@
"doctrine/lexer": "<1.0.2",
"phpunit/phpunit": "<5.4.3",
"symfony/dependency-injection": "<4.4",
"symfony/expression-language": "<5.1",
"symfony/http-kernel": "<4.4",
"symfony/intl": "<4.4",
"symfony/translation": "<4.4",
Expand All @@ -61,7 +62,7 @@
"egulias/email-validator": "Strict (RFC compliant) email validation",
"symfony/property-access": "For accessing properties within comparison constraints",
"symfony/property-info": "To automatically add NotNull and Type constraints",
"symfony/expression-language": "For using the Expression validator"
"symfony/expression-language": "For using the Expression validator and the ExpressionLanguageSyntax constraints"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Validator\\": "" },
Expand Down

0 comments on commit 0d001e7

Please sign in to comment.