8000 [Validator] Add is_valid function to Expression constraint by verdet23 · Pull Request #47153 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] Add is_valid function to Expression constraint #47153

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension 8000

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/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Deprecate the "loose" e-mail validation mode, use "html5" instead
8000 * Add the `negate` option to the `Expression` constraint, to inverse the logic of the violation's creation
* Add `is_valid` function to the `Expression` constraint, its behavior is the same as `ValidatorInterface::validate`

6.1
---
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?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\Validator\Constraints;

use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;

/**
* @author Ihor Khokhlov <eld2303@gmail.com>
*/
class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
public function getFunctions(): array
{
return [
new ExpressionFunction('is_valid', function (...$arguments) {
return sprintf(
'0 === $context->getValidator()->inContext($context)->validate(%s)->getViolations()->count()',
implode(', ', $arguments)
);
}, function (array $variables, ...$arguments): bool {
return 0 === $variables['context']->getValidator()->inContext($variables['context'])->validate(...$arguments)->getViolations()->count();
}),
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class ExpressionValidator extends ConstraintValidator
public function __construct(ExpressionLanguage $expressionLanguage = null)
{
$this->expressionLanguage = $expressionLanguage;
$this->expressionLanguage?->registerProvider(new ExpressionLanguageProvider());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We shouldn't mutate the expression language we receive in the constructor, it would lead to unexpected behavior if the provided expression language is used elsewhere.

}

/**
Expand All @@ -41,6 +42,7 @@ public function validate(mixed $value, Constraint $constraint)
$variables = $constraint->values;
$variables['value'] = $value;
$variables['this'] = $this->context->getObject();
$variables['context'] = $this->context;

if ($constraint->negate xor $this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) {
$this->context->buildViolation($constraint->message)
Expand All @@ -54,6 +56,7 @@ private function getExpressionLanguage(): ExpressionLanguage
{
if (null === $this->expressionLanguage) {
$this->expressionLanguage = new ExpressionLanguage();
$this->expressionLanguage->registerProvider(new ExpressionLanguageProvider());
}

return $this->expressionLanguage;
Expand Down
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 <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Constraints;

use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Validator\Constraints\ExpressionLanguageProvider;
use Symfony\Component\Validator\Constraints\ExpressionValidator;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

class ExpressionLanguageProviderTest extends ConstraintValidatorTestCase
{
protected function createValidator()
{
return new ExpressionValidator();
}

/**
* @dataProvider dataProviderCompile
*/
public function testCompile(string $expression, array $names, string $expected)
{
$provider = new ExpressionLanguageProvider();

$expressionLanguage = new ExpressionLanguage();
$expressionLanguage->registerProvider($provider);

$result = $expressionLanguage->compile($expression, $names);

$this->assertSame($expected, $result);
}

public function dataProviderCompile(): array
{
return [
[
'is_valid("foo", constraints)',
['constraints'],
'0 === $context->getValidator()->inContext($context)->validate("foo", $constraints)->getViolations()->count()',
],
[
'is_valid(this.data, constraints, groups)',
['this', 'constraints', 'groups'],
'0 === $context->getValidator()->inContext($context)->validate($this->data, $constraints, $groups)->getViolations()->count()',
],
];
}

public function testEvaluateValid()
{
$constraints = [new Length(['min' => 2, 'max' => 12])];

$this->expectValidateValue(0, 'foo', $constraints);

$expressionLanguage = new ExpressionLanguage();
$expressionLanguage->registerProvider(new ExpressionLanguageProvider());

$this->assertTrue($expressionLanguage->evaluate('is_valid("foo", a)', ['a' => $constraints, 'context' => $this->context]));
}

public function testEvaluateInvalid()
{
$constraints = [new Length(['min' => 7, 'max' => 12])];

$this->expectFailingValueValidation(
0,
'foo',
$constraints,
null,
new ConstraintViolation('error_length', '', [], '', '', 'foo', null, 'range')
);

$expressionLanguage = new ExpressionLanguage();
$expressionLanguage->registerProvider(new ExpressionLanguageProvider());

$this->assertFalse($expressionLanguage->evaluate('is_valid("foo", a)', ['a' => $constraints, 'context' => $this->context]));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Validator\Constraints\Expression;
use Symfony\Component\Validator\Constraints\ExpressionValidator;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
use Symfony\Component\Validator\Tests\Fixtures\Annotation\Entity;
use Symfony\Component\Validator\Tests\Fixtures\ToString;
Expand Down Expand Up @@ -304,4 +307,50 @@ public function testViolationOnPass()
->setCode(Expression::EXPRESSION_FAILED_ERROR)
->assertRaised();
}

public function testIsValidExpression()
{
$constraints = [new NotNull(), new Range(['min' => 2])];

$constraint = new Expression(
['expression' => 'is_valid(this.data, a)', 'values' => ['a' => $constraints]]
);

$object = new Entity();
$object->data = 7;

$this->setObject($object);

$this->expectValidateValue(0, $object->data, $constraints);

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

$this->assertNoViolation();
}

public function testIsValidExpressionInvalid()
{
$constraints = [new Range(['min' => 2, 'max' => 5])];

$constraint = new Expression(
['expression' => 'is_valid(this.data, a)', 'values' => ['a' => $constraints]]
);

$object = new Entity();
$object->data = 7;

$this->setObject($object);

$this->expectFailingValueValidation(
0,
7,
$constraints,
null,
new ConstraintViolation('error_range', '', [], '', '', 7, null, 'range')
);

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

$this->assertCount(2, $this->context->getViolations());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be $this->assertCount(1, $this->context->getViolations());? Or put the other way: Where is the second violation coming from?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one violation from is_valid, second from expression itself

}
}
0