Callback example

$this->expectValidateValue(0, $number->value, $constraints);

        $this->validator->validate($number->value, new When([
            'expression' => 'this.type === "positive"',
            'constraints' => $constraints,
        ]));
    }

    public function testConstraintsAreExecutedWithValue()
    {
        $constraints = [
            new Callback(),
        ];

        $this->expectValidateValue(0, 'foo', $constraints);

        $this->validator->validate('foo', new When([
            'expression' => 'value === "foo"',
            'constraints' => $constraints,
        ]));
    }

    public function testConstraintsAreExecutedWithExpressionValues()
    {
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([
            new Assert\NotNull(),
            
public function testLoadClassMetadata()
    {
        $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml');
        $metadata = new ClassMetadata(Entity::class);

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata(Entity::class);
        $expected->setGroupSequence(['Foo', 'Entity']);
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new ConstraintB());
        $expected->addConstraint(new Callback('validateMe'));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addConstraint(new Callback(['Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback']));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(['min' => 3]));
        $expected->addPropertyConstraint('firstName', new Choice(['A', 'B']));
        $expected->addPropertyConstraint('firstName', new All([new NotNull()new Range(['min' => 3])]));
        $expected->addPropertyConstraint('firstName', new All(['constraints' => [new NotNull()new Range(['min' => 3])]]));
        $expected->addPropertyConstraint('firstName', new Collection(['fields' => [
            'foo' => [new NotNull()new Range(['min' => 3])],
            'bar' => [new Range(['min' => 5])],
        ]]));
        

class CallbackTest extends MigrateProcessTestCase {

  /** * Tests callback with valid "callable". * * @dataProvider providerCallback */
  public function testCallback($callable) {
    $configuration = ['callable' => $callable];
    $this->plugin = new Callback($configuration, 'map', []);
    $value = $this->plugin->transform('FooBar', $this->migrateExecutable, $this->row, 'destination_property');
    $this->assertSame('foobar', $value);
  }

  /** * Data provider for ::testCallback(). */
  public function providerCallback() {
    return [
      'function' => ['strtolower'],
      'class method' => [[self::class, 'strtolower']],
    ];
$this->assertNull($context->getClassName());
            $this->assertNull($context->getPropertyName());
            $this->assertSame('', $context->getPropertyPath());
            $this->assertSame('Group', $context->getGroup());
            $this->assertSame('Bernhard', $context->getRoot());
            $this->assertSame('Bernhard', $context->getValue());
            $this->assertSame('Bernhard', $value);

            $context->addViolation('Message %param%', ['%param%' => 'value']);
        };

        $constraint = new Callback([
            'callback' => $callback,
            'groups' => 'Group',
        ]);

        $violations = $this->validate('Bernhard', $constraint, 'Group');

        /* @var ConstraintViolationInterface[] $violations */
        $this->assertCount(1, $violations);
        $this->assertSame('Message value', $violations[0]->getMessage());
        $this->assertSame('Message %param%', $violations[0]->getMessageTemplate());
        $this->assertSame(['%param%' => 'value']$violations[0]->getParameters());
        


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(),
        
$this->expectDeprecation('Since symfony/validator 6.4: Property "Symfony\Component\Validator\Tests\Constraints\WhenTestWithAnnotations::$bar" uses Doctrine Annotations to configure validation constraints, which is deprecated. Use PHP attributes instead.');
        $this->expectDeprecation('Since symfony/validator 6.4: Property "Symfony\Component\Validator\Tests\Constraints\WhenTestWithAnnotations::$qux" uses Doctrine Annotations to configure validation constraints, which is deprecated. Use PHP attributes instead.');
        $this->expectDeprecation('Since symfony/validator 6.4: Method "Symfony\Component\Validator\Tests\Constraints\WhenTestWithAnnotations::getBaz()" uses Doctrine Annotations to configure validation constraints, which is deprecated. Use PHP attributes instead.');

        self::assertTrue($loader->loadClassMetadata($metadata));

        [$classConstraint] = $metadata->getConstraints();

        self::assertInstanceOf(When::class$classConstraint);
        self::assertSame('true', $classConstraint->expression);
        self::assertEquals([
            new Callback([
                'callback' => 'callback',
                'groups' => ['Default', 'WhenTestWithAnnotations'],
            ]),
        ]$classConstraint->constraints);

        [$fooConstraint] = $metadata->properties['foo']->getConstraints();

        self::assertInstanceOf(When::class$fooConstraint);
        self::assertSame('true', $fooConstraint->expression);
        self::assertEquals([
            new NotNull([
                
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)}) */
->expects($this->never())
            ->method('getItem');
        $factory->getMetadataFor($testedValue);
    }

    public function testMetadataCacheWithRuntimeConstraint()
    {
        $cache = new ArrayAdapter();
        $factory = new LazyLoadingMetadataFactory(new TestLoader()$cache);

        $metadata = $factory->getMetadataFor(self::PARENT_CLASS);
        $metadata->addConstraint(new Callback(function D) {}));

        $this->assertCount(3, $metadata->getConstraints());

        $metadata = $factory->getMetadataFor(self::CLASS_NAME);

        $this->assertCount(6, $metadata->getConstraints());
    }

    public function testGroupsFromParent()
    {
        $reader = new \Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader();
        

        $loader = $this->createAnnotationLoader();
        $namespace = $this->getFixtureNamespace();

        $metadata = new ClassMetadata($namespace.'\Entity');

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata($namespace.'\Entity');
        $expected->setGroupSequence(['Foo', 'Entity']);
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new Callback(['Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback']));
        $expected->addConstraint(new Sequentially([
            new Expression('this.getFirstName() != null'),
        ]));
        $expected->addConstraint(new Callback(['callback' => 'validateMe', 'payload' => 'foo']));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(['min' => 3]));
        $expected->addPropertyConstraint('firstName', new All([new NotNull()new Range(['min' => 3])]));
        $expected->addPropertyConstraint('firstName', new All(['constraints' => [new NotNull()new Range(['min' => 3])]]));
        $expected->addPropertyConstraint('firstName', new Collection([
            'foo' => [new NotNull()new Range(['min' => 3])],
            


class CallbackValidatorTest extends ConstraintValidatorTestCase
{
    protected function createValidator(): CallbackValidator
    {
        return new CallbackValidator();
    }

    public function testNullIsValid()
    {
        $this->validator->validate(null, new Callback());

        $this->assertNoViolation();
    }

    public function testSingleMethod()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback('validate');

        $this->validator->validate($object$constraint);

        
public function testLoadClassMetadata()
    {
        $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml');
        $metadata = new ClassMetadata(Entity::class);

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata(Entity::class);
        $expected->setGroupSequence(['Foo', 'Entity']);
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new ConstraintB());
        $expected->addConstraint(new Callback('validateMe'));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addConstraint(new Callback(['Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback']));
        $expected->addConstraint(new Traverse(false));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(['min' => 3]));
        $expected->addPropertyConstraint('firstName', new Choice(['A', 'B']));
        $expected->addPropertyConstraint('firstName', new All([new NotNull()new Range(['min' => 3])]));
        $expected->addPropertyConstraint('firstName', new All(['constraints' => [new NotNull()new Range(['min' => 3])]]));
        $expected->addPropertyConstraint('firstName', new Collection(['fields' => [
            'foo' => [new NotNull()new Range(['min' => 3])],
            'bar' => [new Range(['min' => 5])],
        ]]));
Home | Imprint | This part of the site doesn't use cookies.