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

Skip to content

[Validator] Add "is_valid" function to the Expression constraint #33829

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
wants to merge 1 commit into from
Closed
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
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
=========

4.4.0
-----

* Added the `ExpressionLanguage::hasFunction()` method.

4.0.0
-----

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,11 @@ public function registerProvider(ExpressionFunctionProviderInterface $provider)
}
}

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

protected function registerFunctions()
{
$this->addFunction(ExpressionFunction::fromPhp('constant'));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,4 +256,15 @@ function (ExpressionLanguage $el) {
],
];
}

public function testHasFunction()
{
$el = new ExpressionLanguage();

$this->assertFalse($el->hasFunction('foo'));

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

$this->assertTrue($el->hasFunction('foo'));
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md 10000
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ CHANGELOG
* Overriding the methods `ConstraintValidatorTestCase::setUp()` and `ConstraintValidatorTestCase::tearDown()` without the `void` return-type is deprecated.
* deprecated `Symfony\Component\Validator\Mapping\Cache\CacheInterface` in favor of PSR-6.
* deprecated `ValidatorBuilder::setMetadataCache`, use `ValidatorBuilder::setMappingCache` instead.
* Added the `is_valid` function to the `Expression` constraint.

4.3.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\LogicException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

Expand All @@ -39,7 +40,9 @@ public function __construct(/*ExpressionLanguage */$expressionLanguage = null)
@trigger_error(sprintf('The "%s" first argument must be an instance of "%s" or null since 4.4. "%s" given', __METHOD__, ExpressionLanguage::class, \is_object($expressionLanguage) ? \get_class($expressionLanguage) : \gettype($expressionLanguage)), E_USER_DEPRECATED);
}

$this->expressionLanguage = $expressionLanguage;
if (($this->expressionLanguage = $expressionLanguage) instanceof ExpressionLanguage) {
$this->addIsValidFunction();
}
}

/**
Expand All @@ -65,13 +68,87 @@ public function validate($value, Constraint $constraint)

private function getExpressionLanguage()
{
if (null === $this->expressionLanguage) {
if (!$this->expressionLanguage instanceof ExpressionLanguage) {
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
throw new LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
}
$this->expressionLanguage = new ExpressionLanguage();

$this->addIsValidFunction();
}

return $this->expressionLanguage;
}

< EDBE /span>
private function addIsValidFunction(): void
{
if ($this->expressionLanguage->hasFunction('is_valid')) {
return;
}

$this->expressionLanguage->register('is_valid', function () {
Copy link
Member
@yceruto yceruto Oct 3, 2019

Choose a reason for hiding this comment

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

This code should be moved to a dedicated class ExpressionLanguageProvider by implementing ExpressionFunctionProviderInterface and later $this->expressionLanguage->registerProvider(...).

throw new LogicException('The "is_valid" function cannot be compiled.');
}, function (array $variables, ...$arguments): bool {
if (!$arguments) {
throw new ConstraintDefinitionException('The "is_valid" function requires at least one argument.');
}

$isObject = \is_object($object = $this->context->getObject());

$constraints = [];
$properties = [];

foreach ($arguments as $argument) {
if ($argument instanceof Constraint) {
$constraints[] = $argument;

continue;
}

if (\is_array($argument)) {
foreach ($argument as $constraint) {
if (!$constraint instanceof Constraint) {
throw new ConstraintDefinitionException(sprintf('The "is_valid" function only accepts arrays that contain instances of "%s" exclusively, "%s" given.', Constraint::class, \is_object($constraint) ? \get_class($constraint) : \gettype($constraint)));
}

$constraints[] = $constraint;
}

continue;
}

if (\is_string($argument)) {
if (!$isObject) {
throw new ConstraintDefinitionException('The "is_valid" function only accepts strings that represent properties paths when validating an object.');
}

$properties[] = $argument;

continue;
}

throw new ConstraintDefinitionException(sprintf('The "is_valid" function only accepts instances of "%s", arrays of "%s", or strings that represent properties paths (when validating an object), "%s" given.', Constraint::class, Constraint::class, \is_object($argument) ? \get_class($argument) : \gettype($argument)));
}

if (!$constraints && !$properties) {
return true;
}

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

if ($constraints) {
if ($validator->validate($variables['value'], $constraints, $this->context->getGroup())->count()) {
return false;
}
}

foreach ($properties as $property) {
if ($validator->validateProperty($object, $property, $this->context->getGroup())->count()) {
return false;
}
}

return true;
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,20 @@
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Validator\Constraints\Expression;
use Symfony\Component\Validator\Constraints\ExpressionValidator;
use Symfony\Component\Validator\Constraints\IdenticalTo;
use Symfony\Component\Validator\Constraints\IsNull;
use Symfony\Component\Validator\Constraints\NotIdenticalTo;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\Context\ExecutionContext;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory;
use Symfony\Component\Validator\Tests\Fixtures\ToString;
use Symfony\Component\Validator\ValidatorBuilder;
use Symfony\Contracts\Translation\TranslatorInterface;

class ExpressionValidatorTest extends ConstraintValidatorTestCase
{
Expand Down Expand Up @@ -322,4 +333,108 @@ public function testPassingCustomValues()

$this->assertNoViolation();
}

public function testExistingIsValidFunctionIsNotOverridden()
{
$used = false;

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

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

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

$this->assertTrue($used);
}

/**
* @dataProvider isValidFunctionWithInvalidArgumentsProvider
*/
public function testIsValidFunctionWithInvalidArguments(string $expectedMessage, $value, string $expression, array $values)
{
$this->expectException(ConstraintDefinitionException::class);
$this->expectExceptionMessage($expectedMessage);

$this->validator->validate($value, new Expression([
'expression' => $expression,
'values' => $values,
]));
}

public function isValidFunctionWithInvalidArgumentsProvider()
{
return [
['The "is_valid" function requires at least one argument.', null, 'is_valid()', []],
['The "is_valid" function only accepts instances of "Symfony\Component\Validator\Constraint", arrays of "Symfony\Component\Validator\Constraint", or strings that represent properties paths (when validating an object), "ArrayIterator" given.', null, 'is_valid(a)', ['a' => new \ArrayIterator()]],
['The "is_valid" function only accepts instances of "Symfony\Component\Validator\Constraint", arrays of "Symfony\Component\Validator\Constraint", or strings that represent properties paths (when validating an object), "NULL" given.', null, 'is_valid(a)', ['a' => null]],
['The "is_valid" function only accepts arrays that contain instances of "Symfony\Component\Validator\Constraint" exclusively, "ArrayIterator" given.', null, 'is_valid(a)', ['a' => [new \ArrayIterator()]]],
['The "is_valid" function only accepts arrays that contain instances of "Symfony\Component\Validator\Constraint" exclusively, "string" given.', null, 'is_valid(a)', ['a' => ['foo']]],
['The "is_valid" function only accepts strings that represent properties paths when validating an object.', 'foo', 'is_valid("bar")', []],
];
}

/**
* @dataProvider isValidFunctionProvider
*/
public function testIsValidFunction(bool $shouldBeValid, $value, string $expression, array $values = [], string $group = null, array $propertiesConstraints = [])
{
$translator = $this->createMock(TranslatorInterface::class);
$translator->method('trans')->willReturnArgument(0);

$validatorBuilder = new ValidatorBuilder();

$classMetadata = null;
if ($valueIsObject = \is_object($value)) {
$classMetadata = new ClassMetadata(\get_class($value));
foreach ($propertiesConstraints as $property => $constraints) {
$classMetadata->addPropertyConstraints($property, $constraints);
}

$validatorBuilder->setMetadataFactory((new FakeMetadataFactory())->addMetadata($classMetadata));
}

$this->validator->initialize($executionContext = new ExecutionContext(
$validatorBuilder->getValidator(),
$this->root,
$translator
));

$executionContext->setConstraint($constraint = new Expression([
'expression' => $expression,
'values' => $values,
]));
$executionContext->setGroup($group);
$executionContext->setNode($value, $valueIsObject ? $value : null, $classMetadata, '');

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

$this->assertSame($shouldBeValid, !(bool) $executionContext->getViolations()->count());
}

public function isValidFunctionProvider()
{
return [
[true, 'foo', 'is_valid(a) or is_valid(b)', ['a' => new NotIdenticalTo('foo'), 'b' => new IdenticalTo('foo')]],
[false, 'foo', 'is_valid(a) and is_valid(b)', ['a' => new NotIdenticalTo('foo'), 'b' => new IdenticalTo('foo')]],
[false, 'foo', 'is_valid(a, b)', ['a' => new NotIdenticalTo('foo'), 'b' => new IdenticalTo('foo')]],
[false, 'foo', 'is_valid(a)', ['a' => new NotIdenticalTo('foo')]],
[true, 'foo', 'is_valid(a)', ['a' => [new IdenticalTo('foo')]]],
[true, 'foo', 'is_valid(a)', ['a' => new NotIdenticalTo(['value' => 'foo', 'groups' => 'g1'])], 'g2'],
[false, new TestExpressionValidatorObject(), 'is_valid("foo")', [], null, ['foo' => [new NotNull()]]],
[true, new TestExpressionValidatorObject(), 'is_valid("foo")', [], null, ['foo' => [new IsNull()]]],
[true, new TestExpressionValidatorObject(), 'is_valid("foo")'],
[true, new TestExpressionValidatorObject(), 'is_valid("any string")'],
[false, new TestExpressionValidatorObject(), 'is_valid("foo", a)', ['a' => new IsNull()], null, ['foo' => [new IsNull()]]],
[true, new TestExpressionValidatorObject(), 'is_valid(a, "foo")', ['a' => new Type(TestExpressionValidatorObject::class)], null, ['foo' => [new IsNull()]]],
];
}
}

final class TestExpressionValidatorObject
{
public $foo = null;
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ public function hasMetadataFor($class): bool
public function addMetadata($metadata)
{
$this->metadatas[$metadata->getClassName()] = $metadata;

return $this;
}

public function addMetadataForValue($value, MetadataInterface $metadata)
Expand Down
0