createValidator example


    public static function createIsValidCallable(Constraint|ValidatorInterface $constraintOrValidator = null, Constraint ...$constraints): callable
    {
        $validator = $constraintOrValidator;

        if ($constraintOrValidator instanceof Constraint) {
            $constraints = \func_get_args();
            $validator = null;
        }

        $validator ??= self::createValidator();

        return static function Dmixed $value, ConstraintViolationListInterface &$violations = null) use ($constraints$validator): bool {
            $violations = $validator->validate($value$constraints);

            return 0 === $violations->count();
        };
    }

    /** * Creates a new validator. * * If you want to configure the validator, use * {@link createValidatorBuilder()} instead. */
'terms' => new Optional([
          new Type('array'),
          new Collection([
            'Release type' => new Optional([
              new Type('array'),
            ]),
          ]),
        ]),
      ],
      'allowExtraFields' => TRUE,
    ]);
    $violations = Validation::createValidator()->validate($data$collection_constraint);
    if (count($violations)) {
      foreach ($violations as $violation) {
        $violation_messages[] = "Field " . $violation->getPropertyPath() . ": " . $violation->getMessage();
      }
      throw new \UnexpectedValueException('Malformed release data: ' . implode(",\n", $violation_messages));
    }
  }

  /** * Gets the project version. * * @return string * The project version. */

    public function testValidateUniquenessUsingCustomRepositoryMethod(UniqueEntity $constraint)
    {
        $repository = $this->createRepositoryMock();
        $repository->expects($this->once())
            ->method('findByCustom')
            ->willReturn([])
        ;
        $this->em = $this->createEntityManagerMock($repository);
        $this->registry = $this->createRegistryMock($this->em);
        $this->validator = $this->createValidator();
        $this->validator->initialize($this->context);

        $entity1 = new SingleIntIdEntity(1, 'foo');

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

        $this->assertNoViolation();
    }

    /** * @dataProvider provideConstraintsWithCustomRepositoryMethod */
$this->metadata = null;
        $this->object = null;
        $this->value = 'InvalidValue';
        $this->root = 'root';
        $this->propertyPath = 'property.path';

        // Initialize the context with some constraint so that we can         // successfully build a violation.         $this->constraint = new NotNull();

        $this->context = $this->createContext();
        $this->validator = $this->createValidator();
        $this->validator->initialize($this->context);

        $this->defaultLocale = \Locale::getDefault();
        \Locale::setDefault('en');

        $this->expectedViolations = [];
        $this->call = 0;

        $this->setDefaultTimezone('UTC');
    }

    
private readonly ?EntityDefinition $definition = null
    ) {
        if (!$definition instanceof EntityDefinition) {
            return;
        }

        try {
            $definition->getFields();
        } catch (\Throwable $exception) {
            $registry = new StaticDefinitionInstanceRegistry(
                [$definition],
                Validation::createValidator(),
                new StaticEntityWriterGateway()
            );
            $definition->compile($registry);
        }
    }

    /** * @return EntitySearchResult<TEntityCollection> */
    public function search(Criteria $criteria, Context $context): EntitySearchResult
    {
        
// If a violation is expected, then the context's addViolation method will     // be called, otherwise it should not be called.     $context = $this->prophesize(ExecutionContextInterface::class);

    if ($expected_violation) {
      $context->addViolation('@name field is required.', ['@name' => 'Email'])->shouldBeCalledTimes(1);
    }
    else {
      $context->addViolation()->shouldNotBeCalled();
    }

    $validator = $this->createValidator($is_admin);
    $validator->initialize($context->reveal());
    $validator->validate($items$constraint);
  }

  /** * Data provider for ::testValidate(). */
  public static function providerTestValidate() {
    $prophet = new Prophet();
    $cases = [];

    
$this->projectDir = (new TestBootstrapper())->getProjectDir();
    }

    public function testValidateRequirementsValid(): void
    {
        $path = __DIR__ . '/_fixture/SwagRequirementValidTest';
        $path = str_replace($this->projectDir, '', $path);

        $plugin = $this->createPlugin($path);

        try {
            $this->createValidator()->validateRequirements($plugin, Context::createDefaultContext(), 'test');
        } catch (\Exception $e) {
            static::fail('This test should not throw an exception, but threw: ' . $e->getMessage());
        }
        static::assertTrue(true);
    }

    public function testValidateRequirementsSubpackageValid(): void
    {
        $path = __DIR__ . '/_fixture/SwagRequirementValidSubpackageTest';
        $path = str_replace($this->projectDir, '', $path);

        
'title' => $not_blank_constraints,
        'project' => $not_blank_constraints,
        'type' => $not_blank_constraints,
        'link' => $not_blank_constraints,
        'is_psa' => new Choice(['choices' => [1, '1', 0, '0', TRUE, FALSE]]),
        'insecure' => new Type(['type' => 'array']),
      ],
      // Allow unknown fields, in the case that new fields are added to JSON       // feed validation should still pass.       'allowExtraFields' => TRUE,
    ]);
    $violations = Validation::createValidator()->validate($data$collection_constraint);
    if ($violations->count()) {
      foreach ($violations as $violation) {
        $violation_messages[] = "Field " . $violation->getPropertyPath() . ": " . $violation->getMessage();
      }
      throw new \UnexpectedValueException('Malformed security advisory: ' . implode(",\n", $violation_messages));
    }
  }

  /** * Gets the title. * * @return string * The project title. */

class FormValidatorTest extends ConstraintValidatorTestCase
{
    private EventDispatcher $dispatcher;
    private FormFactoryInterface $factory;

    protected function setUp(): void
    {
        $this->dispatcher = new EventDispatcher();
        $this->factory = (new FormFactoryBuilder())
            ->addExtension(new ValidatorExtension(Validation::createValidator()))
            ->getFormFactory();

        parent::setUp();

        $this->constraint = new Form();
    }

    public function testValidate()
    {
        $object = new \stdClass();
        $options = ['validation_groups' => ['group1', 'group2']];
        
$this->metadata = null;
        $this->object = null;
        $this->value = 'InvalidValue';
        $this->root = 'root';
        $this->propertyPath = 'property.path';

        // Initialize the context with some constraint so that we can         // successfully build a violation.         $this->constraint = new NotNull();

        $this->context = $this->createContext();
        $this->validator = $this->createValidator();
        $this->validator->initialize($this->context);

        $this->defaultLocale = \Locale::getDefault();
        \Locale::setDefault('en');

        $this->expectedViolations = [];
        $this->call = 0;

        $this->setDefaultTimezone('UTC');
    }

    
private ValidatorInterface $validator;

    protected function setUp(): void
    {
        $this->metadataFactory = new FakeMetadataFactory();
        $this->metadata = new ClassMetadata(self::ENTITY_CLASS);
        $this->referenceMetadata = new ClassMetadata(self::REFERENCE_CLASS);
        $this->metadataFactory->addMetadata($this->metadata);
        $this->metadataFactory->addMetadata($this->referenceMetadata);
        $this->metadataFactory->addMetadata(new ClassMetadata(LazyProperty::class));

        $this->validator = $this->createValidator($this->metadataFactory);
    }

    protected function validate($value$constraints = null, $groups = null)
    {
        return $this->validator->validate($value$constraints$groups);
    }

    protected function validateProperty($object$propertyName$groups = null)
    {
        return $this->validator->validateProperty($object$propertyName$groups);
    }

    
if ($expected_violation) {
      $context->expects($this->once())
        ->method('addViolation')
        ->with($constraint->message, ['%name' => $name]);
    }
    else {
      $context->expects($this->never())
        ->method('addViolation');
    }

    $validator = $this->createValidator();
    $validator->initialize($context);
    $validator->validate($items$constraint);
  }

  /** * Data provider for ::testValidate(). */
  public function providerTestValidate() {
    $cases = [];

    // Case 1: Validation context should not be touched if no items are passed.
use Symfony\Component\Form\Test\FormPerformanceTestCase;
use Symfony\Component\Validator\Validation;

/** * @author Bernhard Schussek <bschussek@gmail.com> */
class FormValidatorPerformanceTest extends FormPerformanceTestCase
{
    protected function getExtensions()
    {
        return [
            new ValidatorExtension(Validation::createValidator(), false),
        ];
    }

    /** * findClickedButton() used to have an exponential number of calls. * * @group benchmark */
    public function testValidationPerformance()
    {
        $this->setMaxRunningTime(1);

        

    protected function createValidator(): AtLeastOneOfValidator
    {
        return new AtLeastOneOfValidator();
    }

    /** * @dataProvider getValidCombinations */
    public function testValidCombinations($value$constraints)
    {
        $this->assertCount(0, Validation::createValidator()->validate($valuenew AtLeastOneOf($constraints)));
    }

    public static function getValidCombinations()
    {
        return [
            ['symfony', [
                new Length(['min' => 10]),
                new EqualTo(['value' => 'symfony']),
            ]],
            [150, [
                new Range(['min' => 10, 'max' => 20]),
                


    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']);

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