Skip to content

Commit c5d14a6

Browse files
committed
feature #42593 [Validator] Add the When constraint and validator (wuchen90)
This PR was merged into the 6.2 branch. Discussion ---------- [Validator] Add the `When` constraint and validator | Q | A | ------------- | --- | Branch? | 6.2 | Bug fix? | no | New feature? | yes <!-- please update src/**/CHANGELOG.md files --> | Deprecations? | no <!-- please update UPGRADE-*.md and src/**/CHANGELOG.md files --> | License | MIT | Doc PR | symfony/symfony-docs#15722 This constraint allows you to apply constraints validation only if the provided condition is matched. Usage: ```php namespace App\Model; use Symfony\Component\Validator\Constraints as Assert; class Discount { private $type; // 'percent' or 'absolute' /** * `@Assert`\GreaterThan(0) * `@Assert`\When( * expression="this.type == 'percent'", * constraints={`@LessThan`(100, message="The value should be between 0 and 100!")} * ) */ private $value; // ... } ``` See the documentation for details. Commits ------- 9b7bdc9 [Validator] Add the When constraint and validator
2 parents 1608cae + 9b7bdc9 commit c5d14a6

File tree

8 files changed

+598
-0
lines changed

8 files changed

+598
-0
lines changed

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@
223223
use Symfony\Component\Translation\Translator;
224224
use Symfony\Component\Uid\Factory\UuidFactory;
225225
use Symfony\Component\Uid\UuidV4;
226+
use Symfony\Component\Validator\Constraints\WhenValidator;
226227
use Symfony\Component\Validator\ConstraintValidatorInterface;
227228
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
228229
use Symfony\Component\Validator\ObjectInitializerInterface;
@@ -1571,6 +1572,10 @@ private function registerValidationConfiguration(array $config, ContainerBuilder
15711572
if (!class_exists(ExpressionLanguage::class)) {
15721573
$container->removeDefinition('validator.expression_language');
15731574
}
1575+
1576+
if (!class_exists(WhenValidator::class)) {
1577+
$container->removeDefinition('validator.when');
1578+
}
15741579
}
15751580

15761581
private function registerValidatorMapping(ContainerBuilder $container, array $config, array &$files)

src/Symfony/Bundle/FrameworkBundle/Resources/config/validator.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use Symfony\Component\Validator\Constraints\EmailValidator;
1818
use Symfony\Component\Validator\Constraints\ExpressionValidator;
1919
use Symfony\Component\Validator\Constraints\NotCompromisedPasswordValidator;
20+
use Symfony\Component\Validator\Constraints\WhenValidator;
2021
use Symfony\Component\Validator\ContainerConstraintValidatorFactory;
2122
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
2223
use Symfony\Component\Validator\Validation;
@@ -95,6 +96,12 @@
9596
'alias' => NotCompromisedPasswordValidator::class,
9697
])
9798

99+
->set('validator.when', WhenValidator::class)
100+
->args([service('validator.expression_language')->nullOnInvalid()])
101+
->tag('validator.constraint_validator', [
102+
'alias' => WhenValidator::class,
103+
])
104+
98105
->set('validator.property_info_loader', PropertyInfoLoader::class)
99106
->args([
100107
service('property_info'),

src/Symfony/Component/Validator/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ CHANGELOG
44
6.2
55
---
66

7+
* Add the `When` constraint and validator
78
* Deprecate the "loose" e-mail validation mode, use "html5" instead
89
* Add the `negate` option to the `Expression` constraint, to inverse the logic of the violation's creation
910

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Validator\Constraints;
13+
14+
use Symfony\Component\ExpressionLanguage\Expression;
15+
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
16+
use Symfony\Component\Validator\Exception\LogicException;
17+
18+
/**
19+
* @Annotation
20+
* @Target({"CLASS", "PROPERTY", "METHOD", "ANNOTATION"})
21+
*/
22+
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
23+
class When extends Composite
24+
{
25+
public $expression;
26+
public $constraints = [];
27+
public $values = [];
28+
29+
public function __construct(string|Expression|array $expression, array $constraints = null, array $values = null, array $groups = null, $payload = null, array $options = [])
30+
{
31+
if (!class_exists(ExpressionLanguage::class)) {
32+
throw new LogicException(sprintf('The "symfony/expression-language" component is required to use the "%s" constraint. Try running "composer require symfony/expression-language".', __CLASS__));
33+
}
34+
35+
if (\is_array($expression)) {
36+
$options = array_merge($expression, $options);
37+
} else {
38+
$options['expression'] = $expression;
39+
$options['constraints'] = $constraints;
40+
}
41+
42+
if (null !== $groups) {
43+
$options['groups'] = $groups;
44+
}
45+
46+
if (null !== $payload) {
47+
$options['payload'] = $payload;
48+
}
49+
50+
parent::__construct($options);
51+
52+
$this->values = $values ?? $this->values;
53+
}
54+
55+
public function getRequiredOptions(): array
56+
{
57+
return ['expression', 'constraints'];
58+
}
59+
60+
public function getTargets(): string|array
61+
{
62+
return [self::CLASS_CONSTRAINT, self::PROPERTY_CONSTRAINT];
63+
}
64+
65+
protected function getCompositeOption(): string
66+
{
67+
return 'constraints';
68+
}
69+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Validator\Constraints;
13+
14+
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
15+
use Symfony\Component\Validator\Constraint;
16+
use Symfony\Component\Validator\ConstraintValidator;
17+
use Symfony\Component\Validator\Exception\LogicException;
18+
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19+
20+
final class WhenValidator extends ConstraintValidator
21+
{
22+
private ?ExpressionLanguage $expressionLanguage;
23+
24+
public function __construct(ExpressionLanguage $expressionLanguage = null)
25+
{
26+
$this->expressionLanguage = $expressionLanguage;
27+
}
28+
29+
/**
30+
* {@inheritdoc}
31+
*/
32+
public function validate(mixed $value, Constraint $constraint): void
33+
{
34+
if (!$constraint instanceof When) {
35+
throw new UnexpectedTypeException($constraint, When::class);
36+
}
37+
38+
$context = $this->context;
39+
$variables = $constraint->values;
40+
$variables['value'] = $value;
41+
$variables['this'] = $context->getObject();
42+
43+
if ($this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) {
44+
$context->getValidator()->inContext($context)
45+
->validate($value, $constraint->constraints);
46+
}
47+
}
48+
49+
private function getExpressionLanguage(): ExpressionLanguage
50+
{
51+
if (null !== $this->expressionLanguage) {
52+
return $this->expressionLanguage;
53+
}
54+
55+
if (!class_exists(ExpressionLanguage::class)) {
56+
throw new LogicException(sprintf('The "symfony/expression-language" component is required to use the "%s" validator. Try running "composer require symfony/expression-language".', __CLASS__));
57+
}
58+
59+
return $this->expressionLanguage = new ExpressionLanguage();
60+
}
61+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace Symfony\Component\Validator\Tests\Constraints\Fixtures;
4+
5+
use Symfony\Component\Validator\Constraints\Callback;
6+
use Symfony\Component\Validator\Constraints\NotBlank;
7+
use Symfony\Component\Validator\Constraints\NotNull;
8+
use Symfony\Component\Validator\Constraints\When;
9+
10+
#[When(expression: 'true', constraints: [
11+
new Callback('callback'),
12+
])]
13+
class WhenTestWithAttributes
14+
{
15+
#[When(expression: 'true', constraints: [
16+
new NotNull(),
17+
new NotBlank(),
18+
])]
19+
private $foo;
20+
21+
#[When(expression: 'false', constraints: [
22+
new NotNull(),
23+
new NotBlank(),
24+
], groups: ['foo'])]
25+
private $bar;
26+
27+
#[When(expression: 'true', constraints: [
28+
new NotNull(),
29+
new NotBlank(),
30+
])]
31+
public function getBaz()
32+
{
33+
return null;
34+
}
35+
36+
public function callback()
37+
{
38+
}
39+
}

0 commit comments

Comments
 (0)