Skip to content

[Validator] added improve support for collection validation #31196

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

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions UPGRADE-4.4.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ Validator
method in 5.0.
* Deprecated passing an `ExpressionLanguage` instance as the second argument of `ExpressionValidator::__construct()`.
Pass it as the first argument instead.
* Deprecated `All` in favor of `Each` constraint
* Deprecated `AllValidator` in favor of `EachValidator` validator
* The `Length` constraint expects the `allowEmptyString` option to be defined
when the `min` option is used.
Set it to `true` to keep the current behavior and `false` to reject empty strings.
Expand Down
2 changes: 2 additions & 0 deletions UPGRADE-5.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,8 @@ Validator
* The `symfony/intl` component is now required for using the `Bic`, `Country`, `Currency`, `Language` and `Locale` constraints
* The `egulias/email-validator` component is now required for using the `Email` constraint in strict mode
* The `symfony/expression-language` component is now required for using the `Expression` constraint
* Removed `All`, use the `Each` constraint instead.
* Removed `AllValidator`, use the `EachValidator` validator instead.

WebProfilerBundle
-----------------
Expand Down
9 changes: 9 additions & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ CHANGELOG
* added the `compared_value_path` parameter in violations when using any
comparison constraint with the `propertyPath` option.
* added support for checking an array of types in `TypeValidator`
* deprecated `All` in favor of `Each` constraint
* deprecated `AllValidator` in favor of `EachValidator` validator
* added `Each` constraint
* added `EachValidator`
* added `None` constraint
* added `NoneValidator`
Copy link
Member

Choose a reason for hiding this comment

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

I suggest merging this line with the previous one. Adding the new constraint and its validator are a single feature addition (same for other constraints).
Older versions don't mention the validator at all btw, only the new constraint (as that's the relevant user-facing thing)

* added `Some` constraint
* added `SomeValidator`
* added `AbstractComposite` constraint
* added a new `allowEmptyString` option to the `Length` constraint to allow rejecting empty strings when `min` is set, by setting it to `false`.
* Added new `minPropertyPath` and `maxPropertyPath` options
to `Range` constraint in order to get the value to compare
Expand Down
120 changes: 120 additions & 0 deletions src/Symfony/Component/Validator/Constraints/AbstractComposite.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?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\Validator\Constraint;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;

/**
* @Annotation
Copy link
Member

Choose a reason for hiding this comment

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

should be removed. This abstract class is not an annotation by itself.

*
* @author Marc Morales Valldepérez <marcmorales83@gmail.com>
* @author Marc Morera Merino <yuhu@mmoreram.com>
*/
abstract class AbstractComposite extends Composite
{
/**
* @var array
*
* Set of constraints
*/
public $constraints = [];

/**
* {@inheritdoc}
*/
public function __construct($options = null)
{
parent::__construct($options);

$this->constraints = (array) $this->constraints;

// Each constraint contained
foreach ($this->constraints as $constraint) {
if (!$constraint instanceof Constraint) {
throw new ConstraintDefinitionException(sprintf('The value %s is not an instance of Constraint in constraint %s', $constraint, \get_class($this)));
}

if ($constraint instanceof Valid) {
throw new ConstraintDefinitionException(sprintf('The constraint Valid cannot be nested inside constraint %s. You can only declare the Valid constraint directly on a field or method.', \get_class($this)));
}

// If explicit groups are defined
if ($this->groups != [self::DEFAULT_GROUP]) {
/*
* If constraint has explicit groups defined
*
* In that case, the groups of the nested constraint need to be
* a subset of the groups of the outer constraint.
*/
if ($constraint->groups !== [self::DEFAULT_GROUP]) {
// If are not a subset
if ($constraint->groups != array_intersect($constraint->groups, $this->groups)) {
throw new ConstraintDefinitionException(sprintf('The groups defined in Constraint %s must be a subset of the groups defined in the Constraint %s', $constraint, \get_class($this)));
}

// Otherwise, we add all defined groups here
} else {
foreach ($this->groups as $group) {
$constraint->addImplicitGroupName($group);
}
}

/*
* Otherwise, we merge current groups with constraint
*/
} else {
$this->groups = array_unique(array_merge($this->groups, $constraint->groups));
}
}
}

/**
* Adds the given group if this constraint is in the Default group.
*
* Also propagate same method to nested Constraints.
*
* @param string $group
*/
public function addImplicitGroupName($group)
{
parent::addImplicitGroupName($group);

foreach ($this->constraints as $constraint) {
$constraint->addImplicitGroupName($group);
}
}

/**
* {@inheritdoc}
*/
public function getDefaultOption()
{
return 'constraints';
}

/**
* {@inheritdoc}
*/
public function getRequiredOptions()
{
return ['constraints'];
}

/**
* {@inheritdoc}
*/
protected function getCompositeOption()
Copy link
Member

Choose a reason for hiding this comment

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

I do not really see why we need this method.

Copy link
Contributor Author

@Simperfit Simperfit Jul 16, 2019

Choose a reason for hiding this comment

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

to say if it's a contraints or a field, if we remove it, we need to remove it from the abtracts composite too and check if it's a contraints or a field

{
return 'constraints';
}
}
23 changes: 6 additions & 17 deletions src/Symfony/Component/Validator/Constraints/All.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,12 @@
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @api
Copy link
Member

Choose a reason for hiding this comment

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

should be removed. We dropped such tag years ago in favor of @internal and @experimental

*
* @deprecated Deprecated in 4.3, to be removed in 5.0. Use
Copy link
Member

Choose a reason for hiding this comment

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

4.4

Copy link
Member

Choose a reason for hiding this comment

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

and this also needs to trigger a deprecation warning.

* {@link \Symfony\Component\Validator\Constraints\Each} instead.
*/
class All extends Composite
class All extends AbstractComposite
{
public $constraints = [];

public function getDefaultOption()
{
return 'constraints';
}

public function getRequiredOptions()
{
return ['constraints'];
}

protected function getCompositeOption()
{
return 'constraints';
}
}
13 changes: 8 additions & 5 deletions src/Symfony/Component/Validator/Constraints/AllValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@

/**
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @api
*
* @deprecated Deprecated in 4.3, to be removed in 5.0. Use
Copy link
Member

Choose a reason for hiding this comment

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

same issues here

* {@link \Symfony\Component\Validator\Constraints\EachValidator} instead.
*/
class AllValidator extends ConstraintValidator
{
Expand All @@ -27,20 +32,18 @@ class AllValidator extends ConstraintValidator
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof All) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\All');
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Each or '.__NAMESPACE__.'\All');
}

if (null === $value) {
return;
}

if (!\is_array($value) && !$value instanceof \Traversable) {
if (!is_iterable($value)) {
throw new UnexpectedValueException($value, 'iterable');
}

$context = $this->context;

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

foreach ($value as $key => $element) {
$validator->atPath('['.$key.']')->validate($element, $constraint->constraints);
Expand Down
22 changes: 22 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Each.php
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\Validator\Constraints;

/**
* @Annotation
Copy link
Member

Choose a reason for hiding this comment

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

please also add @Target({"PROPERTY", "METHOD", "ANNOTATION"})

*
* @author Marc Morera Merino <yuhu@mmoreram.com>
* @author Marc Morales Valldepérez <marcmorales83@gmail.com>
*/
class Each extends All
Copy link
Member

Choose a reason for hiding this comment

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

We should make the legacy annotation extend the new one instead of the opposite, so that we don't load the legacy code when you use the new annotation.

{
}
21 changes: 21 additions & 0 deletions src/Symfony/Component/Validator/Constraints/EachValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?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;

/**
* @author Marc Morera Merino <yuhu@mmoreram.com>
* @author Marc Morales Valldepérez <marcmorales83@gmail.com>
* @author Hamza Amrouche <hamza.simperfit@gmail.com>
*/
class EachValidator extends AllValidator
{
}
48 changes: 48 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Exactly.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?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\Validator\Exception\MissingOptionsException;

/**
* @Annotation
Copy link
Member

Choose a reason for hiding this comment

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

please also add @Target({"PROPERTY", "METHOD", "ANNOTATION"})

*
* @author Marc Morera Merino <yuhu@mmoreram.com>
* @author Marc Morales Valldepérez <marcmorales83@gmail.com>
*/
class Exactly extends AbstractComposite
{
/**
* @var string
*
* Message for notice Exactly Violation
*/
public $exactlyMessage = 'Exactly {{ limit }} element of this collection should pass validation.|Exactly {{ limit }} elements of this collection should pass validation.';

/**
* @var int
*
* Exactly number of Success expected
*/
public $exactly;

/**
* {@inheritdoc}
*/
public function __construct($options = null)
{
parent::__construct($options);
if (null === $this->exactly) {
throw new MissingOptionsException('The "exactly" option cannot be null', ['exactly']);
Copy link
Member

Choose a reason for hiding this comment

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

why not adding it to required options instead ? It will be validated by the parent.

}
}
}
62 changes: 62 additions & 0 deletions src/Symfony/Component/Validator/Constraints/ExactlyValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?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\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

/**
* @author Hamza Amrouche <hamza.simperfit@gmail.com>
*/
class ExactlyValidator extends ConstraintValidator
Copy link
Member

Choose a reason for hiding this comment

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

I am actually not convinced that we need this validator. What would be a use case for it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

because of #31196 (comment)

{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (null === $value) {
return;
}

if (!$constraint instanceof Exactly) {
throw new UnexpectedTypeException($constraint, Exactly::class);
}

if (!is_iterable($value)) {
throw new UnexpectedValueException($value, 'array or Traversable');
}

$totalIterations = \count($value) * \count($constraint->constraints);

$validator = $this->context->getValidator()->inContext($this->context);
Copy link
Member

Choose a reason for hiding this comment

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

don't validate in the existing context. This will cause issues if other validators have run and have added some violations themselves.
You need to run it on a dedicated context (which is supported precisely for this kind of features).


foreach ($value as $key => $element) {
$validator->atPath('['.$key.']')->validate($element, $constraint->constraints);
}

$constraintsSuccess = $totalIterations - (int) $this->context->getViolations()->count();
$violations = $this->context->getViolations();
// We clear all violations as just current Validator should add real Violations
foreach ($this->context->getViolations() as $key => $violation) {
$violations->remove($key);
}

if (isset($constraint->exactly) && $constraintsSuccess != $constraint->exactly) {
$this->context->buildViolation($constraint->exactlyMessage)
->setParameter('{{ limit }}', $constraint->exactly)
->addViolation();
}
}
}
Loading