Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Validator] Add the When constraint and validator #42593

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

Merged
merged 1 commit into from
Sep 11, 2022
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@
use Symfony\Component\Translation\Translator;
use Symfony\Component\Uid\Factory\UuidFactory;
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Validator\Constraints\WhenValidator;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
use Symfony\Component\Validator\ObjectInitializerInterface;
Expand Down Expand Up @@ -1570,6 +1571,10 @@ private function registerValidationConfiguration(array $config, ContainerBuilder
if (!class_exists(ExpressionLanguage::class)) {
$container->removeDefinition('validator.expression_language');
}

if (!class_exists(WhenValidator::class)) {
$container->removeDefinition('validator.when');
}
}

private function registerValidatorMapping(ContainerBuilder $container, array $config, array &$files)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\Validator\Constraints\EmailValidator;
use Symfony\Component\Validator\Constraints\ExpressionValidator;
use Symfony\Component\Validator\Constraints\NotCompromisedPasswordValidator;
use Symfony\Component\Validator\Constraints\WhenValidator;
use Symfony\Component\Validator\ContainerConstraintValidatorFactory;
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
use Symfony\Component\Validator\Validation;
Expand Down Expand Up @@ -95,6 +96,12 @@
'alias' => NotCompromisedPasswordValidator::class,
])

->set('validator.when', WhenValidator::class)
->args([service('validator.expression_language')->nullOnInvalid()])
->tag('validator.constraint_validator', [
'alias' => WhenValidator::class,
])

->set('validator.property_info_loader', PropertyInfoLoader::class)
->args([
service('property_info'),
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
6.2
---

* Add the `When` constraint and validator
* 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

Expand Down
69 changes: 69 additions & 0 deletions src/Symfony/Component/Validator/Constraints/When.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\Validator\Exception\LogicException;

/**
* @Annotation
* @Target({"CLASS", "PROPERTY", "METHOD", "ANNOTATION"})
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class When extends Composite
{
public $expression;
public $constraints = [];
public $values = [];

public function __construct(string|Expression|array $expression, array $constraints = null, array $values = null, array $groups = null, $payload = null, array $options = [])
{
if (!class_exists(ExpressionLanguage::class)) {
throw new LogicException(sprintf('The "symfony/expression-language" component is required to use the "%s" constraint. Try running "composer require symfony/expression-language".', __CLASS__));
}

if (\is_array($expression)) {
$options = array_merge($expression, $options);
} else {
$options['expression'] = $expression;
$options['constraints'] = $constraints;
}

if (null !== $groups) {
$options['groups'] = $groups;
}

if (null !== $payload) {
$options['payload'] = $payload;
}

parent::__construct($options);

$this->values = $values ?? $this->values;
}

public function getRequiredOptions(): array
{
return ['expression', 'constraints'];
}

public function getTargets(): string|array
{
return [self::CLASS_CONSTRAINT, self::PROPERTY_CONSTRAINT];
}

protected function getCompositeOption(): string
{
return 'constraints';
}
}
61 changes: 61 additions & 0 deletions src/Symfony/Component/Validator/Constraints/WhenValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\ExpressionLanguage;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\LogicException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

final class WhenValidator extends ConstraintValidator
{
private ?ExpressionLanguage $expressionLanguage;

public function __construct(ExpressionLanguage $expressionLanguage = null)
{
$this->expressionLanguage = $expressionLanguage;
}

/**
* {@inheritdoc}
*/
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof When) {
throw new UnexpectedTypeException($constraint, When::class);
}

$context = $this->context;
$variables = $constraint->values;
$variables['value'] = $value;
$variables['this'] = $context->getObject();

if ($this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) {
$context->getValidator()->inContext($context)
->validate($value, $constraint->constraints);
}
}

private function getExpressionLanguage(): ExpressionLanguage
{
if (null !== $this->expressionLanguage) {
return $this->expressionLanguage;
}

if (!class_exists(ExpressionLanguage::class)) {
throw new LogicException(sprintf('The "symfony/expression-language" component is required to use the "%s" validator. Try running "composer require symfony/expression-language".', __CLASS__));
}

return $this->expressionLanguage = new ExpressionLanguage();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Symfony\Component\Validator\Tests\Constraints\Fixtures;

use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\When;

#[When(expression: 'true', constraints: [
new Callback('callback'),
])]
class WhenTestWithAttributes
{
#[When(expression: 'true', constraints: [
new NotNull(),
new NotBlank(),
])]
private $foo;

#[When(expression: 'false', constraints: [
new NotNull(),
new NotBlank(),
], groups: ['foo'])]
private $bar;

#[When(expression: 'true', constraints: [
new NotNull(),
new NotBlank(),
])]
public function getBaz()
{
return null;
}

public function callback()
{
}
}
Loading