10000 [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 1 commit
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
Next Next commit
Add is_valid function to Expression constraint
  • Loading branch information
verdet23 committed Aug 11, 2022
commit 536e2f56b668d19a226b5c80f3b9e150fcdaae28
5 changes: 5 additions & 0 deletions src/Symfony/Component/ExpressionLanguage/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

6.2
---

* Add `ExpressionLanguage::hasFunction()` and `ExpressionLanguage::hasFunctionByName()` methods.

6.1
---

Expand Down
10 changes: 10 additions & 0 deletions src/Symfony/Component/ExpressionLanguage/ExpressionLanguage.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,16 @@ public function addFunction(ExpressionFunction $function)
$this->register($function->getName(), $function->getCompiler(), $function->getEvaluator());
}

public function hasFunction(ExpressionFunction $function): bool
{
return $this->hasFunctionByName($function->getName());
}

public function hasFunctionByName(string $functionName): bool
{
return isset($this->functions[$functionName]);
}

public function registerProvider(ExpressionFunctionProviderInterface $provider)
{
foreach ($provider->getFunctions() as $function) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -384,4 +384,28 @@ function (ExpressionLanguage $el) {
],
];
}

public function testHasFunction(): void
{
$expressionLanguage = new ExpressionLanguage();

$function = new ExpressionFunction('foo', function () {}, function () {});

$this->assertFalse($expressionLanguage->hasFunction($function));

$expressionLanguage->addFunction($function);

$this->assertTrue($expressionLanguage->hasFunction($function));
}

public function testHasFunctionByName(): void
{
$expressionLanguage = new ExpressionLanguage();

$this->assertFalse($expressionLanguage->hasFunctionByName('foo'));

$expressionLanguage->register('foo', function () {}, function () {});

$this->assertTrue($expressionLanguage->hasFunctionByName('foo'));
}
}
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
* 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, api the same as `ValidatorInterface::validate`

6.1
---
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?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 LogicException;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
* Define some ExpressionLanguage functions.
*
* @author Ihor Khokhlov <eld2303@gmail.com>
*/
class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
private ExecutionContextInterface $context;

public function __construct(ExecutionContextInterface $context)
{
$this->context = $context;
}

public function getFunctions(): array
{
return [
new ExpressionFunction('is_valid', function () {
throw new LogicException('The "is_valid" function cannot be compiled.');
}, function (array $variables, ...$arguments): bool {
$context = $this->context;

$validator = $context->getValidator()->inContext($context);

$violations = $validator->validate(...$arguments)->getViolations();

return 0 === $violations->count();
}),
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ private function getExpressionLanguage(): ExpressionLanguage
$this->expressionLanguage = new ExpressionLanguage();
}

if (false === $this->expressionLanguage->hasFunctionByName('is_valid')) {
$this->expressionLanguage->registerProvider(new ExpressionLanguageProvider($this->context));
}

return $this->expressionLanguage;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?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 LogicException;
use PHPUnit\Framework\TestCase;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Validator\Constraints\ExpressionLanguageProvider;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Validator\ContextualValidatorInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class ExpressionLanguageProviderTest extends TestCase
{
public function testCompile(): void
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('The "is_valid" function cannot be compiled.');

$context = $this->createMock(ExecutionContextInterface::class);

$provider = new ExpressionLanguageProvider($context);

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

$expressionLanguage->compile('is_valid()');
}

/**
* @dataProvider dataProviderEvaluate
*/
public function testEvaluate(bool $expected, int $errorsCount): void
{
$constraints = [new NotNull(), new Range(['min' => 2])];

$violationList = $this->getMockBuilder(ConstraintViolationListInterface::class)
->onlyMethods(['count'])
->getMockForAbstractClass();
$violationList->expects($this->once())
->method('count')
->willReturn($errorsCount);

$contextualValidator = $this->getMockBuilder(ContextualValidatorInterface::class)
->onlyMethods(['getViolations', 'validate'])
->getMockForAbstractClass();
$contextualValidator->expects($this->once())
->method('validate')
->with('foo', $constraints)
->willReturnSelf();
$contextualValidator->expects($this->once())
->method('getViolations')
->willReturn($violationList);

$validator = $this->getMockBuilder(ValidatorInterface::class)
->onlyMethods(['inContext'])
->getMockForAbstractClass();

$context = $this->getMockBuilder(ExecutionContextInterface::class)
->onlyMethods(['getValidator'])
->getMockForAbstractClass();
$context->expects($this->once())
->method('getValidator')
->willReturn($validator);

$validator->expects($this->once())
->method('inContext')
->with($context)
->willReturn($contextualValidator);

$provider = new ExpressionLanguageProvider($context);

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

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

public function dataProviderEvaluate(): array
{
return [
[true, 0],
[false, 1],
[false, 12],
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
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\Test\ConstraintValidatorTestCase;
use Symfony\Component\Validator\Tests\Fixtures\Annotation\Entity;
use Symfony\Component\Validator\Tests\Fixtures\ToString;
Expand Down Expand Up @@ -304,4 +306,41 @@ public function testViolationOnPass()
->setCode(Expression::EXPRESSION_FAILED_ERROR)
->assertRaised();
}

public function testIsValidExpression(): void
{
$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 testExistingIsValidFunctionIsNotOverridden(): void
{
$used = false;

$expressionLanguage = new ExpressionLanguage();
$expressionLanguage->register('is_valid', function () {}, function () use (&$used) {
$used = true;
});

$validator = new ExpressionValidator($expressionLanguage);
$validator->initialize($this->context);

$validator->validate('foo', new Expression('is_valid()'));

$this->assertTrue($used);
}
}
0