How to Sequentially Apply Validation Groups

In some cases, you want to validate your groups by steps. To do this, you can use the GroupSequence feature. In this case, an object defines a group sequence, which determines the order groups should be validated.

場合によっては、グループを段階的に検証する必要があります。これを行うには、GroupSequence 機能を使用できます。この場合、オブジェクトは、グループを検証する順序を決定する groupssequence を定義します。

For example, suppose you have a User class and want to validate that the username and the password are different only if all other validation passes (in order to avoid multiple error messages).

たとえば、User クラスがあり、(複数のエラー メッセージを回避するために) 他のすべての検証に合格した場合にのみ、ユーザー名とパスワードが異なることを検証したいとします。
  • Attributes
    属性
  • YAML
    YAML
  • XML
    XML
  • PHP
    PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/Entity/User.php
namespace App\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;

#[Assert\GroupSequence(['User', 'Strict'])]
class User implements UserInterface
{
    #[Assert\NotBlank]
    private $username;

    #[Assert\NotBlank]
    private $password;

    #[Assert\IsTrue(
        message: 'The password cannot match your username',
        groups: ['Strict'],
    )]
    public function isPasswordSafe()
    {
        return ($this->username !== $this->password);
    }
}

In this example, it will first validate all constraints in the group User (which is the same as the Default group). Only if all constraints in that group are valid, the second group, Strict, will be validated.

この例では、最初にユーザー グループ (デフォルト グループと同じ) のすべての制約を検証します。そのグループのすべての制約が有効な場合にのみ、2 番目のグループである Strict が検証されます。

Caution

注意

As you have already seen in How to Apply only a Subset of all Your Validation Constraints (Validation Groups), the Default group and the group containing the class name (e.g. User) were identical. However, when using Group Sequences, they are no longer identical. The Default group will now reference the group sequence, instead of all constraints that do not belong to any group.

すべての検証制約 (検証グループ) のサブセットのみを適用する方法で既に説明したように、デフォルト グループとクラス名 (ユーザーなど) を含むグループは同一でした。ただし、グループ シーケンスを使用する場合、それらは同一ではなくなります.デフォルト グループは、どのグループにも属さないすべての制約ではなく、グループ シーケンスを参照するようになりました。

This means that you have to use the {ClassName} (e.g. User) group when specifying a group sequence. When using Default, you get an infinite recursion (as the Default group references the group sequence, which will contain the Default group which references the same group sequence, ...).

これは、グループ シーケンスを指定するときに {ClassName} (例: User) グループを使用する必要があることを意味します。 Default を使用すると、無限の再帰が得られます (Default グループは同じグループ シーケンスを参照する Default グループを含むグループ シーケンスを参照するため、...)。

Caution

注意

Calling validate() with a group in the sequence (Strict in previous example) will cause a validation only with that group and not with all the groups in the sequence. This is because sequence is now referred to Default group validation.

シーケンス内のグループ (前の例では Strict) で validate() を呼び出すと、シーケンス内のすべてのグループではなく、そのグループでのみ検証が行われます。これは、シーケンスがデフォルトのグループ検証に参照されるようになったためです。

You can also define a group sequence in the validation_groups form option:

また、validation_groups フォーム オプションでグループ シーケンスを定義することもできます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/Form/MyType.php
namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\GroupSequence;
// ...

class MyType extends AbstractType
{
    // ...
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'validation_groups' => new GroupSequence(['First', 'Second']),
        ]);
    }
}

Group Sequence Providers

Imagine a User entity which can be a normal user or a premium user. When it's a premium user, some extra constraints should be added to the user entity (e.g. the credit card details). To dynamically determine which groups should be activated, you can create a Group Sequence Provider. First, create the entity and a new constraint group called Premium:

通常のユーザーまたはプレミアム ユーザーになることができる User エンティティを想像してください。プレミアム ユーザーの場合、ユーザー エンティティに追加の制約を追加する必要があります (クレジット カードの詳細など)。どのグループをアクティブにする必要があるかを動的に決定するために、グループ シーケンス プロバイダーを作成できます。まず、エンティティと Premium という新しい制約グループを作成します。
  • Attributes
    属性
  • YAML
    YAML
  • XML
    XML
  • PHP
    PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/Entity/User.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class User
{
    #[Assert\NotBlank]
    private $name;

    #[Assert\CardScheme(
        schemes: [Assert\CardScheme::VISA],
        groups: ['Premium'],
    )]
    private $creditCard;

    // ...
}

Now, change the User class to implement GroupSequenceProviderInterface and add the getGroupSequence(), method, which should return an array of groups to use:

次に、User クラスを変更して、GroupSequenceProviderInterface を実装し、使用するグループの配列を返す getGroupSequence() メソッドを追加します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/Entity/User.php
namespace App\Entity;

// ...
use Symfony\Component\Validator\GroupSequenceProviderInterface;

class User implements GroupSequenceProviderInterface
{
    // ...

    public function getGroupSequence(): array|GroupSequence
    {
        // when returning a simple array, if there's a violation in any group
        // the rest of the groups are not validated. E.g. if 'User' fails,
        // 'Premium' and 'Api' are not validated:
        return ['User', 'Premium', 'Api'];

        // when returning a nested array, all the groups included in each array
        // are validated. E.g. if 'User' fails, 'Premium' is also validated
        // (and you'll get its violations too) but 'Api' won't be validated:
        return [['User', 'Premium'], 'Api'];
    }
}

At last, you have to notify the Validator component that your User class provides a sequence of groups to be validated:

最後に、検証する一連のグループを User クラスが提供することを Validator コンポーネントに通知する必要があります。
  • Attributes
    属性
  • YAML
    YAML
  • XML
    XML
  • PHP
    PHP
1
2
3
4
5
6
7
8
9
10
// src/Entity/User.php
namespace App\Entity;

// ...

#[Assert\GroupSequenceProvider]
class User implements GroupSequenceProviderInterface
{
    // ...
}

How to Sequentially Apply Constraints on a Single Property

Sometimes, you may want to apply constraints sequentially on a single property. The Sequentially constraint can solve this for you in a more straightforward way than using a GroupSequence.

場合によっては、1 つのプロパティに順番に制約を適用したい場合があります。 Sequentially 制約は、GroupSequence を使用するよりも簡単な方法でこれを解決できます。