Skip to content

Commit

Permalink
use named-arguments to configure validation constraint options
Browse files Browse the repository at this point in the history
  • Loading branch information
xabbuh committed Jan 24, 2025
1 parent 171af72 commit 8499a9c
Show file tree
Hide file tree
Showing 15 changed files with 82 additions and 164 deletions.
8 changes: 4 additions & 4 deletions components/console/helpers/questionhelper.rst
Original file line number Diff line number Diff line change
Expand Up @@ -480,10 +480,10 @@ invalid answer and will only be able to proceed if their input is valid.
use Symfony\Component\Validator\Validation;

$question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
$validation = Validation::createCallable(new Regex([
'pattern' => '/^[a-zA-Z]+Bundle$/',
'message' => 'The name of the bundle should be suffixed with \'Bundle\'',
]));
$validation = Validation::createCallable(new Regex(
pattern: '/^[a-zA-Z]+Bundle$/',
message: 'The name of the bundle should be suffixed with \'Bundle\'',
));
$question->setValidator($validation);

Validating a Hidden Response
Expand Down
2 changes: 1 addition & 1 deletion components/options_resolver.rst
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ returns ``true`` for acceptable values and ``false`` for invalid values::

// ...
$resolver->setAllowedValues('transport', Validation::createIsValidCallable(
new Length(['min' => 10 ])
new Length(min: 10)
));

In sub-classes, you can use :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::addAllowedValues`
Expand Down
2 changes: 1 addition & 1 deletion components/validator.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ characters long::

$validator = Validation::createValidator();
$violations = $validator->validate('Bernhard', [
new Length(['min' => 10]),
new Length(min: 10),
new NotBlank(),
]);

Expand Down
8 changes: 4 additions & 4 deletions components/validator/metadata.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ the ``Author`` class has at least 3 characters::
$metadata->addPropertyConstraint('firstName', new Assert\NotBlank());
$metadata->addPropertyConstraint(
'firstName',
new Assert\Length(["min" => 3])
new Assert\Length(min: 3)
);
}
}
Expand Down Expand Up @@ -55,9 +55,9 @@ Then, add the Validator component configuration to the class::
{
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue([
'message' => 'The password cannot match your first name',
]));
$metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue(
message: 'The password cannot match your first name',
));
}
}

Expand Down
8 changes: 4 additions & 4 deletions components/validator/resources.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ In this example, the validation metadata is retrieved executing the
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('name', new Assert\NotBlank());
$metadata->addPropertyConstraint('name', new Assert\Length([
'min' => 5,
'max' => 20,
]));
$metadata->addPropertyConstraint('name', new Assert\Length(
min: 5,
max: 20,
));
}
}

Expand Down
10 changes: 5 additions & 5 deletions controller/upload_file.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,14 @@ so Symfony doesn't try to get/set its value from the related entity::
// unmapped fields can't define their validation using attributes
// in the associated entity, so you can use the PHP constraint classes
'constraints' => [
new File([
'maxSize' => '1024k',
'mimeTypes' => [
new File(
maxSize: '1024k',
mimeTypes: [
'application/pdf',
'application/x-pdf',
],
'mimeTypesMessage' => 'Please upload a valid PDF document',
])
mimeTypesMessage: 'Please upload a valid PDF document',
)
],
])
// ...
Expand Down
8 changes: 4 additions & 4 deletions form/without_class.rst
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,12 @@ but here's a short example::
{
$builder
->add('firstName', TextType::class, [
'constraints' => new Length(['min' => 3]),
'constraints' => new Length(min: 3),
])
->add('lastName', TextType::class, [
'constraints' => [
new NotBlank(),
new Length(['min' => 3]),
new Length(min: 3),
],
])
;
Expand Down Expand Up @@ -153,10 +153,10 @@ This can be done by setting the ``constraints`` option in the
$resolver->setDefaults([
'data_class' => null,
'constraints' => new Collection([
'firstName' => new Length(['min' => 3]),
'firstName' => new Length(min: 3),
'lastName' => [
new NotBlank(),
new Length(['min' => 3]),
new Length(min: 3),
],
]),
]);
Expand Down
2 changes: 1 addition & 1 deletion reference/constraints/All.rst
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ entry in that array:
$metadata->addPropertyConstraint('favoriteColors', new Assert\All([
'constraints' => [
new Assert\NotBlank(),
new Assert\Length(['min' => 5]),
new Assert\Length(min: 5),
],
]));
}
Expand Down
12 changes: 6 additions & 6 deletions reference/constraints/AtLeastOneOf.rst
Original file line number Diff line number Diff line change
Expand Up @@ -117,19 +117,19 @@ The following constraints ensure that:
{
$metadata->addPropertyConstraint('password', new Assert\AtLeastOneOf([
'constraints' => [
new Assert\Regex(['pattern' => '/#/']),
new Assert\Length(['min' => 10]),
new Assert\Regex(pattern: '/#/'),
new Assert\Length(min: 10),
],
]));
$metadata->addPropertyConstraint('grades', new Assert\AtLeastOneOf([
'constraints' => [
new Assert\Count(['min' => 3]),
new Assert\All([
'constraints' => [
new Assert\Count(min: 3),
new Assert\All(
'constraints: [

Check failure on line 129 in reference/constraints/AtLeastOneOf.rst

View workflow job for this annotation

GitHub Actions / Code Blocks

[PHP syntax] Syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
new Assert\GreaterThanOrEqual(5),
],
]),
),
],
]));
}
Expand Down
100 changes: 8 additions & 92 deletions validation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -327,99 +327,15 @@ literature genre mostly associated with the author, which can be set to either
{
// ...
$metadata->addPropertyConstraint('genre', new Assert\Choice([
'choices' => ['fiction', 'non-fiction'],
'message' => 'Choose a valid genre.',
]));
$metadata->addPropertyConstraint('genre', new Assert\Choice(
choices: ['fiction', 'non-fiction'],
message: 'Choose a valid genre.',
));
}
}
.. _validation-default-option:

The options of a constraint can always be passed in as an array. Some constraints,
however, also allow you to pass the value of one, "*default*", option in place
of the array. In the case of the ``Choice`` constraint, the ``choices``
options can be specified in this way.

.. configuration-block::

.. code-block:: php-attributes
// src/Entity/Author.php
namespace App\Entity;
// ...
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
#[Assert\Choice(['fiction', 'non-fiction'])]
private string $genre;
// ...
}
.. code-block:: yaml
# config/validator/validation.yaml
App\Entity\Author:
properties:
genre:
- Choice: [fiction, non-fiction]
# ...
.. code-block:: xml
<!-- config/validator/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="App\Entity\Author">
<property name="genre">
<constraint name="Choice">
<value>fiction</value>
<value>non-fiction</value>
</constraint>
</property>
<!-- ... -->
</class>
</constraint-mapping>
.. code-block:: php
// src/Entity/Author.php
namespace App\Entity;
// ...
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
class Author
{
private string $genre;
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
// ...
$metadata->addPropertyConstraint(
'genre',
new Assert\Choice(['fiction', 'non-fiction'])
);
}
}
This is purely meant to make the configuration of the most common option of
a constraint shorter and quicker.

If you're ever unsure of how to specify an option, either check the namespace
``Symfony\Component\Validator\Constraints`` for the constraint or play it safe
by always passing in an array of options (the first method shown above).

Constraints in Form Classes
---------------------------

Expand Down Expand Up @@ -520,7 +436,7 @@ class to have at least 3 characters.
$metadata->addPropertyConstraint('firstName', new Assert\NotBlank());
$metadata->addPropertyConstraint(
'firstName',
new Assert\Length(['min' => 3])
new Assert\Length(min: 3)
);
}
}
Expand Down Expand Up @@ -603,9 +519,9 @@ this method must return ``true``:
{
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue([
'message' => 'The password cannot match your first name',
]));
$metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue(
message: 'The password cannot match your first name',
));
}
}
Expand Down
12 changes: 7 additions & 5 deletions validation/custom_constraint.rst
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ You can use custom validators like the ones provided by Symfony itself:
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('name', new NotBlank());
$metadata->addPropertyConstraint('name', new ContainsAlphanumeric(['mode' => 'loose']));
$metadata->addPropertyConstraint('name', new ContainsAlphanumeric(mode: 'loose'));
}
}
Expand All @@ -273,6 +273,7 @@ define those options as public properties on the constraint class::
// src/Validator/Foo.php
namespace App\Validator;

use Symfony\Component\Validator\Attribute\HasNamedArguments;
use Symfony\Component\Validator\Constraint;

#[\Attribute]
Expand All @@ -282,6 +283,7 @@ define those options as public properties on the constraint class::
public $message = 'This value is invalid';
public $optionalBarOption = false;

#[HasNamedArguments]
public function __construct(
$mandatoryFooOption,
?string $message = null,
Expand Down Expand Up @@ -402,10 +404,10 @@ the custom options like you pass any other option in built-in constraints:
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('name', new NotBlank());
$metadata->addPropertyConstraint('name', new Foo([
'mandatoryFooOption' => 'bar',
'optionalBarOption' => true,
]));
$metadata->addPropertyConstraint('name', new Foo(
mandatoryFooOption: 'bar',
optionalBarOption: true,
));
}
}
Expand Down
30 changes: 15 additions & 15 deletions validation/groups.rst
Original file line number Diff line number Diff line change
Expand Up @@ -101,21 +101,21 @@ user registers and when a user updates their contact information later:
{
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('email', new Assert\Email([
'groups' => ['registration'],
]));
$metadata->addPropertyConstraint('password', new Assert\NotBlank([
'groups' => ['registration'],
]));
$metadata->addPropertyConstraint('password', new Assert\Length([
'min' => 7,
'groups' => ['registration'],
]));
$metadata->addPropertyConstraint('city', new Assert\Length([
'min' => 2,
]));
$metadata->addPropertyConstraint('email', new Assert\Email(
groups: ['registration'],
));
$metadata->addPropertyConstraint('password', new Assert\NotBlank(
groups: ['registration'],
));
$metadata->addPropertyConstraint('password', new Assert\Length(
min: 7,
groups: ['registration'],
));
$metadata->addPropertyConstraint('city', new Assert\Length(
min: 2,
));
}
}
Expand Down
16 changes: 8 additions & 8 deletions validation/sequence_provider.rst
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,10 @@ username and the password are different only if all other validation passes
$metadata->addPropertyConstraint('username', new Assert\NotBlank());
$metadata->addPropertyConstraint('password', new Assert\NotBlank());
$metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue([
'message' => 'The password cannot match your first name',
'groups' => ['Strict'],
]));
$metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue(
message: 'The password cannot match your first name',
groups: ['Strict'],
));
$metadata->setGroupSequence(['User', 'Strict']);
}
Expand Down Expand Up @@ -249,10 +249,10 @@ entity and a new constraint group called ``Premium``:
public static function loadValidatorMetadata(ClassMetadata $metadata): void
{
$metadata->addPropertyConstraint('name', new Assert\NotBlank());
$metadata->addPropertyConstraint('creditCard', new Assert\CardScheme([
'schemes' => [Assert\CardScheme::VISA],
'groups' => ['Premium'],
]));
$metadata->addPropertyConstraint('creditCard', new Assert\CardScheme(
schemes: [Assert\CardScheme::VISA],
groups: ['Premium'],
));
}
}
Expand Down
Loading

0 comments on commit 8499a9c

Please sign in to comment.