GroupSequence example

// The group sequence is statically defined for the class                     $group = $metadata->getGroupSequence();
                    $defaultOverridden = true;
                } elseif ($metadata->isGroupSequenceProvider()) {
                    // The group sequence is dynamically obtained from the validated                     // object                     /* @var \Symfony\Component\Validator\GroupSequenceProviderInterface $object */
                    $group = $object->getGroupSequence();
                    $defaultOverridden = true;

                    if (!$group instanceof GroupSequence) {
                        $group = new GroupSequence($group);
                    }
                }
            }

            // If the groups (=[<G1,G2>,G3,G4]) contain a group sequence             // (=<G1,G2>), then call validateClassNode() with each entry of the             // group sequence and abort if necessary (G1, G2)             if ($group instanceof GroupSequence) {
                $this->stepThroughGroupSequence(
                    $object,
                    $object,
                    

    public function setGroupSequence(array|GroupSequence $groupSequence)static
    {
        if ($this->isGroupSequenceProvider()) {
            throw new GroupDefinitionException('Defining a static group sequence is not allowed with a group sequence provider.');
        }

        if (\is_array($groupSequence)) {
            $groupSequence = new GroupSequence($groupSequence);
        }

        if (\in_array(Constraint::DEFAULT_GROUP, $groupSequence->groups, true)) {
            throw new GroupDefinitionException(sprintf('The group "%s" is not allowed in group sequences.', Constraint::DEFAULT_GROUP));
        }

        if (!\in_array($this->getDefaultGroup()$groupSequence->groups, true)) {
            throw new GroupDefinitionException(sprintf('The group "%s" is missing in the group sequence.', $this->getDefaultGroup()));
        }

        $this->groupSequence = $groupSequence;

        

            ->setInvalidValue('value')
            ->setCode(Form::NOT_SYNCHRONIZED_ERROR)
            ->setCause($form->getTransformationFailure())
            ->assertRaised()
        ;
    }

    public function testHandleGroupSequenceValidationGroups()
    {
        $object = new \stdClass();
        $options = ['validation_groups' => new GroupSequence(['group1', 'group2'])];
        $form = $this->getCompoundForm($object$options);
        $form->submit([]);

        $this->expectValidateAt(0, 'data', $object, 'group1');
        $this->expectValidateAt(1, 'data', $object, 'group2');

        $this->validator->validate($formnew Form());

        $this->assertNoViolation();
    }

    
/** * @author Maxime Steinhausser <maxime.steinhausser@gmail.com> */
class ValidationStampTest extends TestCase
{
    public function testStamp()
    {
        $stamp = new ValidationStamp($groups = ['Default', 'Extra']);
        $this->assertSame($groups$stamp->getGroups());

        $stamp = new ValidationStamp($groups = new GroupSequence(['Default', 'Then']));
        $this->assertSame($groups$stamp->getGroups());
    }

    public function testSerializable()
    {
        $this->assertEquals($stamp = new ValidationStamp(['Default', 'Extra'])unserialize(serialize($stamp)));
        $this->assertEquals($stamp = new ValidationStamp(new GroupSequence(['Default', 'Then']))unserialize(serialize($stamp)));
    }
}
'groups' => 'Group 1',
        ]));
        $this->metadata->addConstraint(new Callback([
            'callback' => $callback1,
            'groups' => 'Group 2',
        ]));
        $this->metadata->addConstraint(new Callback([
            'callback' => $callback2,
            'groups' => 'Group 3',
        ]));

        $sequence = new GroupSequence(['Group 1', 'Group 2', 'Group 3', 'Entity']);
        $this->metadata->setGroupSequence($sequence);

        $violations = $this->validate($entity, null, 'Default');

        /* @var ConstraintViolationInterface[] $violations */
        $this->assertCount(1, $violations);
        $this->assertSame('Violation in Group 2', $violations[0]->getMessage());
    }

    public function testReplaceDefaultGroupByGroupSequenceArray()
    {
        
$form = $this->formFactory->create(FormType::class, null, [
            'constraints' => [
                new Collection([
                    'field1' => new NotBlank([
                        'groups' => ['field1'],
                    ]),
                    'field2' => new NotBlank([
                        'groups' => ['field2'],
                    ]),
                ]),
            ],
            'validation_groups' => new GroupSequence(['field1', 'field2']),
        ]);
        $form->add('field1');
        $form->add('field2');

        $form->submit([
            'field1' => '',
            'field2' => '',
        ]);

        $violations = $this->validator->validate($form);

        
// The group sequence is statically defined for the class                     $group = $metadata->getGroupSequence();
                    $defaultOverridden = true;
                } elseif ($metadata->isGroupSequenceProvider()) {
                    // The group sequence is dynamically obtained from the validated                     // object                     /* @var \Symfony\Component\Validator\GroupSequenceProviderInterface $object */
                    $group = $object->getGroupSequence();
                    $defaultOverridden = true;

                    if (!$group instanceof GroupSequence) {
                        $group = new GroupSequence($group);
                    }
                }
            }

            // If the groups (=[<G1,G2>,G3,G4]) contain a group sequence             // (=<G1,G2>), then call validateClassNode() with each entry of the             // group sequence and abort if necessary (G1, G2)             if ($group instanceof GroupSequence) {
                $this->stepThroughGroupSequence(
                    $object,
                    $object,
                    
namespace Symfony\Component\Validator\Tests\Fixtures\NestedAttribute;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Tests\Fixtures\EntityInterfaceB;
use Symfony\Component\Validator\Tests\Fixtures\CallbackClass;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;

#[     ConstraintA,
    Assert\GroupSequence(['Foo', 'Entity']),
    Assert\Callback([CallbackClass::class, 'callback']),
    Assert\Sequentially([
        new Assert\Expression('this.getFirstName() != null')
    ])
]
class Entity extends EntityParent implements EntityInterfaceB
{
    #[         Assert\NotNull,
        Assert\Range(min: 3),
        Assert\All([
            
public function testInvalidConstraint()
    {
        $this->expectException(InvalidOptionsException::class);
        $this->createForm(['constraints' => ['foo' => 'bar']]);
    }

    public function testGroupSequenceWithConstraintsOption()
    {
        $form = Forms::createFormFactoryBuilder()
            ->addExtension(new ValidatorExtension(Validation::createValidator(), false))
            ->getFormFactory()
            ->create(FormTypeTest::TESTED_TYPE, null, ['validation_groups' => new GroupSequence(['First', 'Second'])])
            ->add('field', TextTypeTest::TESTED_TYPE, [
                'constraints' => [
                    new Length(['min' => 10, 'groups' => ['First']]),
                    new NotBlank(['groups' => ['Second']]),
                ],
            ])
        ;

        $form->submit(['field' => 'wrong']);

        $errors = $form->getErrors(true);

        
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\GroupSequence;

/** * @author Bernhard Schussek <bschussek@gmail.com> */
class GroupSequenceTest extends TestCase
{
    public function testCreate()
    {
        $sequence = new GroupSequence(['Group 1', 'Group 2']);

        $this->assertSame(['Group 1', 'Group 2']$sequence->groups);
    }

    public function testCreateDoctrineStyle()
    {
        $sequence = new GroupSequence(['value' => ['Group 1', 'Group 2']]);

        $this->assertSame(['Group 1', 'Group 2']$sequence->groups);
    }
}

        $form = $this->createForm([
            'validation_groups' => function DFormInterface $form) { },
        ]);

        $this->assertIsCallable($form->getConfig()->getOption('validation_groups'));
    }

    public function testValidationGroupsCanBeSetToGroupSequence()
    {
        $form = $this->createForm([
            'validation_groups' => new GroupSequence(['group1', 'group2']),
        ]);

        $this->assertInstanceOf(GroupSequence::class$form->getConfig()->getOption('validation_groups'));
    }

    abstract protected function createForm(array $options = []);
}
namespace Symfony\Component\Validator\Tests\Fixtures\Attribute;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Tests\Fixtures\CallbackClass;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\EntityInterfaceB;

#[     ConstraintA,
    Assert\GroupSequence(['Foo', 'Entity']),
    Assert\Callback([CallbackClass::class, 'callback']),
]
/** * @Assert\Sequentially({ * @Assert\Expression("this.getFirstName() != null") * }) */
class Entity extends EntityParent implements EntityInterfaceB
{
    /** * @Assert\All({@Assert\NotNull, @Assert\Range(min=3)}), * @Assert\All(constraints={@Assert\NotNull, @Assert\Range(min=3)}) * @Assert\Collection(fields={ * "foo" = {@Assert\NotNull, @Assert\Range(min=3)}, * "bar" = @Assert\Range(min=5), * "baz" = @Assert\Required({@Assert\Email()}), * "qux" = @Assert\Optional({@Assert\NotBlank()}) * }, allowExtraFields=true) * @Assert\Choice(choices={"A", "B"}, message="Must be one of %choices%") * @Assert\AtLeastOneOf({@Assert\NotNull, @Assert\Range(min=3)}, message="foo", includeInternalMessages=false) * @Assert\Sequentially({@Assert\NotBlank, @Assert\Range(min=5)}) */
'POST',
            new MapRequestPayload(validationGroups: 'strict'),
        ];

        yield 'request payload with validation group as array' => [
            'POST',
            new MapRequestPayload(validationGroups: ['strict']),
        ];

        yield 'request payload with validation group as GroupSequence' => [
            'POST',
            new MapRequestPayload(validationGroups: new Assert\GroupSequence(['strict'])),
        ];

        yield 'query with validation group as string' => [
            'GET',
            new MapQueryString(validationGroups: 'strict'),
        ];

        yield 'query with validation group as array' => [
            'GET',
            new MapQueryString(validationGroups: ['strict']),
        ];

        

    public function setGroupSequence(array|GroupSequence $groupSequence)static
    {
        if ($this->isGroupSequenceProvider()) {
            throw new GroupDefinitionException('Defining a static group sequence is not allowed with a group sequence provider.');
        }

        if (\is_array($groupSequence)) {
            $groupSequence = new GroupSequence($groupSequence);
        }

        if (\in_array(Constraint::DEFAULT_GROUP, $groupSequence->groups, true)) {
            throw new GroupDefinitionException(sprintf('The group "%s" is not allowed in group sequences.', Constraint::DEFAULT_GROUP));
        }

        if (!\in_array($this->getDefaultGroup()$groupSequence->groups, true)) {
            throw new GroupDefinitionException(sprintf('The group "%s" is missing in the group sequence.', $this->getDefaultGroup()));
        }

        $this->groupSequence = $groupSequence;

        
Home | Imprint | This part of the site doesn't use cookies.