static function loadValidatorMetadata(ClassMetadata $metadatas)
 {
     $metadatas->addConstraint(new Unique(array('fields' => 'name')));
     $metadatas->addConstraint(new Unique(array('fields' => 'role')));
     $metadatas->addPropertyConstraint("name", new Length(array('min' => 4, "max" => 100)));
     $metadatas->addPropertyConstraint("role", new Length(array('min' => 6, "max" => 100)));
     $metadatas->addPropertyConstraint("role", new Regex(array('pattern' => "/^ROLE\\_/", "message" => "The value must begin by 'ROLE_'")));
 }
 /** validate user entity */
 static function loadValidatorMetadata(ClassMetadata $metadata)
 {
     $metadata->addConstraint(new UniqueEntity(array("username")));
     $metadata->addConstraint(new UniqueEntity(array("email")));
     $metadata->addPropertyConstraint("username", new NotNull());
     $metadata->addPropertyConstraint("username", new Length(array("min" => 5, "max" => 100)));
     $metadata->addPropertyConstraint("email", new NotNull());
     $metadata->addPropertyConstraint("email", new Length(array("min" => 5, "max" => 100)));
     $metadata->addPropertyConstraint("password", new NotNull());
     $metadata->addPropertyConstraint("password", new Length(array("min" => 5, "max" => 100)));
 }
 /**
  * {@inheritDoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     $reflClass = $metadata->getReflectionClass();
     $className = $reflClass->getName();
     $loaded = false;
     foreach ($this->reader->getClassAnnotations($reflClass) as $constraint) {
         if ($constraint instanceof Set) {
             foreach ($constraint->constraints as $constraint) {
                 $metadata->addConstraint($constraint);
             }
         } elseif ($constraint instanceof GroupSequence) {
             $metadata->setGroupSequence($constraint->groups);
         } elseif ($constraint instanceof Constraint) {
             $metadata->addConstraint($constraint);
         }
         $loaded = true;
     }
     foreach ($reflClass->getProperties() as $property) {
         if ($property->getDeclaringClass()->getName() == $className) {
             foreach ($this->reader->getPropertyAnnotations($property) as $constraint) {
                 if ($constraint instanceof Set) {
                     foreach ($constraint->constraints as $constraint) {
                         $metadata->addPropertyConstraint($property->getName(), $constraint);
                     }
                 } elseif ($constraint instanceof Constraint) {
                     $metadata->addPropertyConstraint($property->getName(), $constraint);
                 }
                 $loaded = true;
             }
         }
     }
     foreach ($reflClass->getMethods() as $method) {
         if ($method->getDeclaringClass()->getName() == $className) {
             foreach ($this->reader->getMethodAnnotations($method) as $constraint) {
                 // TODO: clean this up
                 $name = lcfirst(substr($method->getName(), 0, 3) == 'get' ? substr($method->getName(), 3) : substr($method->getName(), 2));
                 if ($constraint instanceof Set) {
                     foreach ($constraint->constraints as $constraint) {
                         $metadata->addGetterConstraint($name, $constraint);
                     }
                 } elseif ($constraint instanceof Constraint) {
                     $metadata->addGetterConstraint($name, $constraint);
                 }
                 $loaded = true;
             }
         }
     }
     return $loaded;
 }
Exemple #4
0
 /**
  * {@inheritDoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     if (null === $this->classes) {
         $this->classes = Yaml::load($this->file);
     }
     // TODO validation
     if (isset($this->classes[$metadata->getClassName()])) {
         $yaml = $this->classes[$metadata->getClassName()];
         if (isset($yaml['constraints'])) {
             foreach ($this->parseNodes($yaml['constraints']) as $constraint) {
                 $metadata->addConstraint($constraint);
             }
         }
         if (isset($yaml['properties'])) {
             foreach ($yaml['properties'] as $property => $constraints) {
                 foreach ($this->parseNodes($constraints) as $constraint) {
                     $metadata->addPropertyConstraint($property, $constraint);
                 }
             }
         }
         if (isset($yaml['getters'])) {
             foreach ($yaml['getters'] as $getter => $constraints) {
                 foreach ($this->parseNodes($constraints) as $constraint) {
                     $metadata->addGetterConstraint($getter, $constraint);
                 }
             }
         }
         return true;
     }
     return false;
 }
 public function testInitializeObjectsOnFirstValidation()
 {
     $test = $this;
     $entity = new Entity();
     $entity->initialized = false;
     // prepare initializers that set "initialized" to true
     $initializer1 = $this->getMock('Symfony\\Component\\Validator\\ObjectInitializerInterface');
     $initializer2 = $this->getMock('Symfony\\Component\\Validator\\ObjectInitializerInterface');
     $initializer1->expects($this->once())->method('initialize')->with($entity)->will($this->returnCallback(function ($object) {
         $object->initialized = true;
     }));
     $initializer2->expects($this->once())->method('initialize')->with($entity);
     $this->visitor = new ValidationVisitor('Root', $this->metadataFactory, new ConstraintValidatorFactory(), new DefaultTranslator(), null, array($initializer1, $initializer2));
     // prepare constraint which
     // * checks that "initialized" is set to true
     // * validates the object again
     $callback = function ($object, ExecutionContextInterface $context) use($test) {
         $test->assertTrue($object->initialized);
         // validate again in same group
         $context->validate($object);
         // validate again in other group
         $context->validate($object, '', 'SomeGroup');
     };
     $this->metadata->addConstraint(new Callback(array($callback)));
     $this->visitor->validate($entity, 'Default', '');
     $this->assertTrue($entity->initialized);
 }
 /**
  * This is a functinoal test as there is a large integration necessary to get the validator working.
  */
 public function testValidateUniqueness()
 {
     $entityManagerName = "foo";
     $em = $this->createTestEntityManager();
     $schemaTool = new SchemaTool($em);
     $schemaTool->createSchema(array($em->getClassMetadata('Symfony\\Tests\\Bridge\\Doctrine\\Form\\Fixtures\\SingleIdentEntity')));
     $entity1 = new SingleIdentEntity(1, 'Foo');
     $registry = $this->createRegistryMock($entityManagerName, $em);
     $uniqueValidator = new UniqueEntityValidator($registry);
     $metadata = new ClassMetadata('Symfony\\Tests\\Bridge\\Doctrine\\Form\\Fixtures\\SingleIdentEntity');
     $metadata->addConstraint(new UniqueEntity(array('fields' => array('name'), 'em' => $entityManagerName)));
     $metadataFactory = $this->createMetadataFactoryMock($metadata);
     $validatorFactory = $this->createValidatorFactory($uniqueValidator);
     $validator = new Validator($metadataFactory, $validatorFactory);
     $violationsList = $validator->validate($entity1);
     $this->assertEquals(0, $violationsList->count(), "No violations found on entity before it is saved to the database.");
     $em->persist($entity1);
     $em->flush();
     $violationsList = $validator->validate($entity1);
     $this->assertEquals(0, $violationsList->count(), "No violations found on entity after it was saved to the database.");
     $entity2 = new SingleIdentEntity(2, 'Foo');
     $violationsList = $validator->validate($entity2);
     $this->assertEquals(1, $violationsList->count(), "No violations found on entity after it was saved to the database.");
     $violation = $violationsList[0];
     $this->assertEquals('This value is already used.', $violation->getMessage());
     $this->assertEquals('name', $violation->getPropertyPath());
     $this->assertEquals('Foo', $violation->getInvalidValue());
 }
 /**
  * {@inheritDoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     if (null === $this->classes) {
         $this->classes = array();
         $xml = $this->parseFile($this->file);
         foreach ($xml->namespace as $namespace) {
             $this->namespaces[(string) $namespace['prefix']] = trim((string) $namespace);
         }
         foreach ($xml->class as $class) {
             $this->classes[(string) $class['name']] = $class;
         }
     }
     if (isset($this->classes[$metadata->getClassName()])) {
         $xml = $this->classes[$metadata->getClassName()];
         foreach ($this->parseConstraints($xml->constraint) as $constraint) {
             $metadata->addConstraint($constraint);
         }
         foreach ($xml->property as $property) {
             foreach ($this->parseConstraints($property->constraint) as $constraint) {
                 $metadata->addPropertyConstraint((string) $property['name'], $constraint);
             }
         }
         foreach ($xml->getter as $getter) {
             foreach ($this->parseConstraints($getter->constraint) as $constraint) {
                 $metadata->addGetterConstraint((string) $getter['property'], $constraint);
             }
         }
         return true;
     }
     return false;
 }
 /**
  * {@inheritDoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     $annotClass = 'Symfony\\Component\\Validator\\Constraints\\Validation';
     $reflClass = $metadata->getReflectionClass();
     $loaded = false;
     if ($annot = $this->reader->getClassAnnotation($reflClass, $annotClass)) {
         foreach ($annot->constraints as $constraint) {
             $metadata->addConstraint($constraint);
         }
         $loaded = true;
     }
     foreach ($reflClass->getProperties() as $property) {
         if ($annot = $this->reader->getPropertyAnnotation($property, $annotClass)) {
             foreach ($annot->constraints as $constraint) {
                 $metadata->addPropertyConstraint($property->getName(), $constraint);
             }
             $loaded = true;
         }
     }
     foreach ($reflClass->getMethods() as $method) {
         if ($annot = $this->reader->getMethodAnnotation($method, $annotClass)) {
             foreach ($annot->constraints as $constraint) {
                 // TODO: clean this up
                 $name = lcfirst(substr($method->getName(), 0, 3) == 'get' ? substr($method->getName(), 3) : substr($method->getName(), 2));
                 $metadata->addGetterConstraint($name, $constraint);
             }
             $loaded = true;
         }
     }
     return $loaded;
 }
 public static function loadValidatorMetadata(ClassMetadata $metadata)
 {
     $metadata->addConstraint(new Callback('validate'));
     $metadata->addPropertyConstraint('password', new NotBlank());
     $metadata->addPropertyConstraint('password', new Length(array('min' => 8, 'max' => 40)));
     $metadata->addPropertyConstraint('repeatPassword', new NotBlank());
     $metadata->addPropertyConstraint('repeatPassword', new Length(array('min' => 8, 'max' => 40)));
 }
Exemple #10
0
 public static function loadValidatorMetadata(ClassMetadata $metadata)
 {
     $metadata->addConstraint(new Callback('checkPassword'));
     $metadata->addPropertyConstraint('password', new NotBlank());
     $metadata->addPropertyConstraint('password', new Length(array('min' => 8, 'max' => 40)));
     $metadata->addPropertyConstraint('email', new Length(array('min' => 2, 'max' => 100)));
     $metadata->addPropertyConstraint('email', new Email());
 }
 /**
  * {@inheritdoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     $reflClass = $metadata->getReflectionClass();
     $className = $reflClass->name;
     $success = false;
     foreach ($this->reader->getClassAnnotations($reflClass) as $constraint) {
         if ($constraint instanceof GroupSequence) {
             $metadata->setGroupSequence($constraint->groups);
         } elseif ($constraint instanceof GroupSequenceProvider) {
             $metadata->setGroupSequenceProvider(true);
         } elseif ($constraint instanceof Constraint) {
             $metadata->addConstraint($constraint);
         }
         $success = true;
     }
     foreach ($reflClass->getProperties() as $property) {
         if ($property->getDeclaringClass()->name == $className) {
             foreach ($this->reader->getPropertyAnnotations($property) as $constraint) {
                 if ($constraint instanceof Constraint) {
                     $metadata->addPropertyConstraint($property->name, $constraint);
                 }
                 $success = true;
             }
         }
     }
     foreach ($reflClass->getMethods() as $method) {
         if ($method->getDeclaringClass()->name == $className) {
             foreach ($this->reader->getMethodAnnotations($method) as $constraint) {
                 if ($constraint instanceof Callback) {
                     $constraint->callback = $method->getName();
                     $constraint->methods = null;
                     $metadata->addConstraint($constraint);
                 } elseif ($constraint instanceof Constraint) {
                     if (preg_match('/^(get|is|has)(.+)$/i', $method->name, $matches)) {
                         $metadata->addGetterConstraint(lcfirst($matches[2]), $constraint);
                     } else {
                         throw new MappingException(sprintf('The constraint on "%s::%s" cannot be added. Constraints can only be added on methods beginning with "get", "is" or "has".', $className, $method->name));
                     }
                 }
                 $success = true;
             }
         }
     }
     return $success;
 }
Exemple #12
0
 /**
  * Test MetaData merge with parent annotation.
  */
 public function testLoadClassMetadataAndMerge()
 {
     $loader = new AnnotationLoader();
     // Load Parent MetaData
     $parent_metadata = new ClassMetadata('Symfony\\Tests\\Component\\Validator\\Fixtures\\EntityParent');
     $loader->loadClassMetadata($parent_metadata);
     $metadata = new ClassMetadata('Symfony\\Tests\\Component\\Validator\\Fixtures\\Entity');
     // Merge parent metaData.
     $metadata->mergeConstraints($parent_metadata);
     $loader->loadClassMetadata($metadata);
     $expected_parent = new ClassMetadata('Symfony\\Tests\\Component\\Validator\\Fixtures\\EntityParent');
     $expected_parent->addPropertyConstraint('other', new NotNull());
     $expected_parent->getReflectionClass();
     $expected = new ClassMetadata('Symfony\\Tests\\Component\\Validator\\Fixtures\\Entity');
     $expected->mergeConstraints($expected_parent);
     $expected->addConstraint(new NotNull());
     $expected->addConstraint(new ConstraintA());
     $expected->addConstraint(new Min(3));
     $expected->addConstraint(new Choice(array('A', 'B')));
     $expected->addConstraint(new All(array(new NotNull(), new Min(3))));
     $expected->addConstraint(new All(array('constraints' => array(new NotNull(), new Min(3)))));
     $expected->addConstraint(new Collection(array('fields' => array('foo' => array(new NotNull(), new Min(3)), 'bar' => new Min(5)))));
     $expected->addPropertyConstraint('firstName', new Choice(array('message' => 'Must be one of %choices%', 'choices' => array('A', 'B'))));
     $expected->addGetterConstraint('lastName', new NotNull());
     // load reflection class so that the comparison passes
     $expected->getReflectionClass();
     $this->assertEquals($expected, $metadata);
 }
 public function testMergeConstraintsMergesClassConstraints()
 {
     $parent = new ClassMetadata(self::PARENTCLASS);
     $parent->addConstraint(new ConstraintA());
     $this->metadata->mergeConstraints($parent);
     $this->metadata->addConstraint(new ConstraintA());
     $constraints = array(new ConstraintA(array('groups' => array('Default', 'EntityParent', 'Entity'))), new ConstraintA(array('groups' => array('Default', 'Entity'))));
     $this->assertEquals($constraints, $this->metadata->getConstraints());
 }
Exemple #14
0
 public function testLoadClassMetadata()
 {
     $loader = new XmlFileLoader(__DIR__ . '/constraint-mapping.xml');
     $metadata = new ClassMetadata('Symfony\\Tests\\Component\\Validator\\Fixtures\\Entity');
     $loader->loadClassMetadata($metadata);
     $expected = new ClassMetadata('Symfony\\Tests\\Component\\Validator\\Fixtures\\Entity');
     $expected->addConstraint(new ConstraintA());
     $expected->addConstraint(new ConstraintB());
     $expected->addPropertyConstraint('firstName', new NotNull());
     $expected->addPropertyConstraint('firstName', new Min(3));
     $expected->addPropertyConstraint('firstName', new Choice(array('A', 'B')));
     $expected->addPropertyConstraint('firstName', new All(array(new NotNull(), new Min(3))));
     $expected->addPropertyConstraint('firstName', new All(array('constraints' => array(new NotNull(), new Min(3)))));
     $expected->addPropertyConstraint('firstName', new Collection(array('fields' => array('foo' => array(new NotNull(), new Min(3)), 'bar' => array(new Min(5))))));
     $expected->addPropertyConstraint('firstName', new Choice(array('message' => 'Must be one of %choices%', 'choices' => array('A', 'B'))));
     $expected->addGetterConstraint('lastName', new NotNull());
     $this->assertEquals($expected, $metadata);
 }
 public static function loadValidatorMetadata(ClassMetadata $metadata)
 {
     $callbackConstraintOptions = array('groups' => 'flow_revalidatePreviousSteps_step1');
     if (Kernel::VERSION_ID < 20400) {
         $callbackConstraintOptions['methods'] = array('isDataValid');
     } else {
         $callbackConstraintOptions['callback'] = 'isDataValid';
     }
     $metadata->addConstraint(new Assert\Callback($callbackConstraintOptions));
 }
 public function createValidator($entityManagerName, $em)
 {
     $registry = $this->createRegistryMock($entityManagerName, $em);
     $uniqueValidator = new UniqueEntityValidator($registry);
     $metadata = new ClassMetadata('Symfony\\Tests\\Bridge\\Doctrine\\Form\\Fixtures\\SingleIdentEntity');
     $metadata->addConstraint(new UniqueEntity(array('fields' => array('name'), 'em' => $entityManagerName)));
     $metadataFactory = $this->createMetadataFactoryMock($metadata);
     $validatorFactory = $this->createValidatorFactory($uniqueValidator);
     return new Validator($metadataFactory, $validatorFactory);
 }
 /**
  * {@inheritDoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     if (null === $this->classes) {
         $this->classes = Yaml::parse($this->file);
         // empty file
         if (null === $this->classes) {
             return false;
         }
         // not an array
         if (!is_array($this->classes)) {
             throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $this->file));
         }
         if (isset($this->classes['namespaces'])) {
             foreach ($this->classes['namespaces'] as $alias => $namespace) {
                 $this->addNamespaceAlias($alias, $namespace);
             }
             unset($this->classes['namespaces']);
         }
     }
     // TODO validation
     if (isset($this->classes[$metadata->getClassName()])) {
         $yaml = $this->classes[$metadata->getClassName()];
         if (isset($yaml['group_sequence_provider'])) {
             $metadata->setGroupSequenceProvider((bool) $yaml['group_sequence_provider']);
         }
         if (isset($yaml['group_sequence'])) {
             $metadata->setGroupSequence($yaml['group_sequence']);
         }
         if (isset($yaml['constraints']) && is_array($yaml['constraints'])) {
             foreach ($this->parseNodes($yaml['constraints']) as $constraint) {
                 $metadata->addConstraint($constraint);
             }
         }
         if (isset($yaml['properties']) && is_array($yaml['properties'])) {
             foreach ($yaml['properties'] as $property => $constraints) {
                 if (null !== $constraints) {
                     foreach ($this->parseNodes($constraints) as $constraint) {
                         $metadata->addPropertyConstraint($property, $constraint);
                     }
                 }
             }
         }
         if (isset($yaml['getters']) && is_array($yaml['getters'])) {
             foreach ($yaml['getters'] as $getter => $constraints) {
                 if (null !== $constraints) {
                     foreach ($this->parseNodes($constraints) as $constraint) {
                         $metadata->addGetterConstraint($getter, $constraint);
                     }
                 }
             }
         }
         return true;
     }
     return false;
 }
 /**
  * Validation for the properties of this Entity
  *
  * @static
  * @param \Symfony\Component\Validator\Mapping\ClassMetadata $metadata
  */
 public static function loadValidatorMetadata(ClassMetadata $metadata)
 {
     // Name should never be NULL or a blank string
     $metadata->addPropertyConstraint('name', new Assert\NotNull(array('groups' => array('create'))));
     $metadata->addPropertyConstraint('name', new Assert\NotBlank(array('groups' => array('create'))));
     // Domain status has fixed set of options and is required
     $metadata->addPropertyConstraint('domainStatus', new Assert\Choice(array('groups' => array('create', 'update'), 'choices' => array('active', 'closed', 'locked', 'pending', 'maintenance'))));
     $metadata->addPropertyConstraint('domainStatus', new Assert\NotNull(array('groups' => array('create'))));
     // DefaultCosId should either be a non-blank string or NULL
     $metadata->addConstraint(new Assert\Callback(array('_validateDefaultCosId')));
 }
 public function testValidateCascadedPropertyRecursesIfDeepIsSet()
 {
     $entity = new Entity();
     $entity->reference = new \ArrayIterator(array('key' => new \ArrayIterator(array('nested' => new Entity()))));
     // add a constraint for the entity that always fails
     $this->metadata->addConstraint(new FailingConstraint());
     // validate iterator when validating the property "reference"
     $this->metadata->addPropertyConstraint('reference', new Valid(array('deep' => true)));
     $this->visitor->validate($entity, 'Default', '');
     $violations = new ConstraintViolationList(array(new ConstraintViolation('Failed', 'Failed', array(), 'Root', '', $entity), new ConstraintViolation('Failed', 'Failed', array(), 'Root', 'reference[key][nested]', $entity->reference['key']['nested'])));
     $this->assertEquals($violations, $this->visitor->getViolations());
 }
Exemple #20
0
 public function testLoadClassMetadata()
 {
     $loader = new XmlFileLoader(__DIR__ . '/constraint-mapping.xml');
     $metadata = new ClassMetadata('Symfony\\Component\\Validator\\Tests\\Fixtures\\Entity');
     $loader->loadClassMetadata($metadata);
     $expected = new ClassMetadata('Symfony\\Component\\Validator\\Tests\\Fixtures\\Entity');
     $expected->setGroupSequence(array('Foo', 'Entity'));
     $expected->addConstraint(new ConstraintA());
     $expected->addConstraint(new ConstraintB());
     $expected->addConstraint(new Callback('validateMe'));
     $expected->addConstraint(new Callback('validateMeStatic'));
     $expected->addConstraint(new Callback(array('Symfony\\Component\\Validator\\Tests\\Fixtures\\CallbackClass', 'callback')));
     $expected->addConstraint(new Traverse(false));
     $expected->addPropertyConstraint('firstName', new NotNull());
     $expected->addPropertyConstraint('firstName', new Range(array('min' => 3)));
     $expected->addPropertyConstraint('firstName', new Choice(array('A', 'B')));
     $expected->addPropertyConstraint('firstName', new All(array(new NotNull(), new Range(array('min' => 3)))));
     $expected->addPropertyConstraint('firstName', new All(array('constraints' => array(new NotNull(), new Range(array('min' => 3))))));
     $expected->addPropertyConstraint('firstName', new Collection(array('fields' => array('foo' => array(new NotNull(), new Range(array('min' => 3))), 'bar' => array(new Range(array('min' => 5)))))));
     $expected->addPropertyConstraint('firstName', new Choice(array('message' => 'Must be one of %choices%', 'choices' => array('A', 'B'))));
     $expected->addGetterConstraint('lastName', new NotNull());
     $expected->addGetterConstraint('valid', new IsTrue());
     $expected->addGetterConstraint('permissions', new IsTrue());
     $this->assertEquals($expected, $metadata);
 }
 public static function loadValidatorMetadata(ClassMetadata $metadata)
 {
     $metadata->addPropertyConstraint('debitQuantity', new Assert\Range(['min' => 0, 'max' => 65535]));
     $metadata->addPropertyConstraint('creditQuantity', new Assert\Range(['min' => 0, 'max' => 65535]));
     $metadata->addConstraint(new Assert\Callback(function (InventoryTransaction $inventoryTransaction, ExecutionContextInterface $context) {
         if (!$inventoryTransaction->isQuantityValid()) {
             $context->buildViolation('Only DebitQuantity or CreditQuantity should be set')->atPath('debitQuantity')->addViolation();
             $context->buildViolation('Only DebitQuantity or CreditQuantity should be set')->atPath('creditQuantity')->addViolation();
         }
     }));
     $metadata->addPropertyConstraint('memo', new Assert\NotBlank());
     $metadata->addPropertyConstraint('memo', new Assert\Length(['max' => 255]));
     $metadata->addPropertyConstraint('product', new Assert\NotNull());
     $metadata->addPropertyConstraint('product', new Assert\Valid());
     $metadata->addPropertyConstraint('inventoryLocation', new Assert\Valid());
     $metadata->addPropertyConstraint('type', new Assert\Valid());
     $metadata->addConstraint(new Assert\Callback(function (InventoryTransaction $inventoryTransaction, ExecutionContextInterface $context) {
         if (!$inventoryTransaction->isLocationValidForMoveOperation()) {
             $context->buildViolation('InventoryLocation must be set for Move operation')->atPath('inventoryLocation')->addViolation();
         }
     }));
 }
Exemple #22
0
 public static function loadValidatorMetadata(ClassMetadata $metadata)
 {
     $metadata->addConstraint(new Callback('validate'));
     $metadata->addPropertyConstraint('subject', new NotBlank());
     $metadata->addPropertyConstraint('subject', new Length(array('min' => 5, 'max' => 100)));
     $metadata->addPropertyConstraint('content', new NotBlank());
     $metadata->addPropertyConstraint('content', new Length(array('min' => 20, 'max' => 3000)));
     $metadata->addPropertyConstraint('authorName', new NotBlank());
     $metadata->addPropertyConstraint('authorName', new Length(array('min' => 5, 'max' => 50)));
     $metadata->addPropertyConstraint('authorEmail', new Length(array('min' => 5, 'max' => 100)));
     $metadata->addPropertyConstraint('authorEmail', new Email());
     $metadata->addPropertyConstraint('authorPhone', new Length(array('min' => 9, 'max' => 30)));
     $metadata->addPropertyConstraint('authorPhone', new Regex(array('pattern' => '/^[0-9\\-\\+ ]{9,16}$/', 'htmlPattern' => '^[0-9\\-\\+ ]{9,16}$', 'message' => 'This is not a valid phone number.')));
 }
Exemple #23
0
 public function testWalkClassInGroupSequencePropagatesDefaultGroup()
 {
     $entity = new Entity();
     $entity->reference = new Reference();
     $this->metadata->addPropertyConstraint('reference', new Valid());
     $this->metadata->setGroupSequence(array($this->metadata->getDefaultGroup()));
     $referenceMetadata = new ClassMetadata(get_class($entity->reference));
     $referenceMetadata->addConstraint(new FailingConstraint(array('groups' => 'Default')));
     $this->factory->addClassMetadata($referenceMetadata);
     $this->walker->walkClass($this->metadata, $entity, 'Default', '');
     // The validation of the reference's FailingConstraint in group
     // "Default" was launched
     $violations = new ConstraintViolationList();
     $violations->add(new ConstraintViolation('', array(), 'Root', 'reference', $entity->reference));
     $this->assertEquals($violations, $this->walker->getViolations());
 }
 public function createValidator($entityManagerName, $em, $validateClass = null, $uniqueFields = null, $errorPath = null, $repositoryMethod = 'findBy', $ignoreNull = true)
 {
     if (!$validateClass) {
         $validateClass = 'Symfony\\Bridge\\Doctrine\\Tests\\Fixtures\\SingleIdentEntity';
     }
     if (!$uniqueFields) {
         $uniqueFields = array('name');
     }
     $registry = $this->createRegistryMock($entityManagerName, $em);
     $uniqueValidator = new UniqueEntityValidator($registry);
     $metadata = new ClassMetadata($validateClass);
     $constraint = new UniqueEntity(array('fields' => $uniqueFields, 'em' => $entityManagerName, 'errorPath' => $errorPath, 'repositoryMethod' => $repositoryMethod, 'ignoreNull' => $ignoreNull));
     $metadata->addConstraint($constraint);
     $metadataFactory = $this->createMetadataFactoryMock($metadata);
     $validatorFactory = $this->createValidatorFactory($uniqueValidator);
     return new Validator($metadataFactory, $validatorFactory);
 }
    public function createValidator($entityManagerName, $em, $validateClass = null, $uniqueFields = null)
    {
        if (!$validateClass) {
            $validateClass = 'Symfony\Tests\Bridge\Doctrine\Fixtures\SingleIdentEntity';
        }
        if (!$uniqueFields) {
            $uniqueFields = array('name');
        }

        $registry = $this->createRegistryMock($entityManagerName, $em);

        $uniqueValidator = new UniqueEntityValidator($registry);

        $metadata = new ClassMetadata($validateClass);
        $metadata->addConstraint(new UniqueEntity(array('fields' => $uniqueFields, 'em' => $entityManagerName)));

        $metadataFactory = $this->createMetadataFactoryMock($metadata);
        $validatorFactory = $this->createValidatorFactory($uniqueValidator);

        return new Validator($metadataFactory, $validatorFactory);
    }
 /**
  * {@inheritDoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     if (null === $this->classes) {
         $this->classes = array();
         $xml = $this->parseFile($this->file);
         foreach ($xml->namespace as $namespace) {
             $this->addNamespaceAlias((string) $namespace['prefix'], trim((string) $namespace));
         }
         foreach ($xml->class as $class) {
             $this->classes[(string) $class['name']] = $class;
         }
     }
     if (isset($this->classes[$metadata->getClassName()])) {
         $xml = $this->classes[$metadata->getClassName()];
         foreach ($xml->{'group-sequence-provider'} as $provider) {
             $metadata->setGroupSequenceProvider(true);
         }
         foreach ($xml->{'group-sequence'} as $groupSequence) {
             if (count($groupSequence->value) > 0) {
                 $metadata->setGroupSequence($this->parseValues($groupSequence[0]->value));
             }
         }
         foreach ($this->parseConstraints($xml->constraint) as $constraint) {
             $metadata->addConstraint($constraint);
         }
         foreach ($xml->property as $property) {
             foreach ($this->parseConstraints($property->constraint) as $constraint) {
                 $metadata->addPropertyConstraint((string) $property['name'], $constraint);
             }
         }
         foreach ($xml->getter as $getter) {
             foreach ($this->parseConstraints($getter->constraint) as $constraint) {
                 $metadata->addGetterConstraint((string) $getter['property'], $constraint);
             }
         }
         return true;
     }
     return false;
 }
Exemple #27
0
 /**
  * {@inheritDoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     if (null === $this->classes) {
         $this->classes = Yaml::load($this->file);
     }
     // empty file
     if (null === $this->classes) {
         return false;
     }
     // not an array
     if (!is_array($this->classes)) {
         throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $this->file));
     }
     // TODO validation
     if (isset($this->classes[$metadata->getClassName()])) {
         $yaml = $this->classes[$metadata->getClassName()];
         if (isset($yaml['constraints'])) {
             foreach ($this->parseNodes($yaml['constraints']) as $constraint) {
                 $metadata->addConstraint($constraint);
             }
         }
         if (isset($yaml['properties'])) {
             foreach ($yaml['properties'] as $property => $constraints) {
                 foreach ($this->parseNodes($constraints) as $constraint) {
                     $metadata->addPropertyConstraint($property, $constraint);
                 }
             }
         }
         if (isset($yaml['getters'])) {
             foreach ($yaml['getters'] as $getter => $constraints) {
                 foreach ($this->parseNodes($constraints) as $constraint) {
                     $metadata->addGetterConstraint($getter, $constraint);
                 }
             }
         }
         return true;
     }
     return false;
 }
 public function testReplaceDefaultGroupWithArrayFromGroupSequenceProvider()
 {
     $sequence = array('Group 1', 'Group 2', 'Group 3', 'Entity');
     $entity = new GroupSequenceProviderEntity($sequence);
     $callback1 = function ($value, ExecutionContextInterface $context) {
         $context->addViolation('Violation in Group 2');
     };
     $callback2 = function ($value, ExecutionContextInterface $context) {
         $context->addViolation('Violation in Group 3');
     };
     $metadata = new ClassMetadata(get_class($entity));
     $metadata->addConstraint(new Callback(array('callback' => function () {
     }, 'groups' => 'Group 1')));
     $metadata->addConstraint(new Callback(array('callback' => $callback1, 'groups' => 'Group 2')));
     $metadata->addConstraint(new Callback(array('callback' => $callback2, 'groups' => 'Group 3')));
     $metadata->setGroupSequenceProvider(true);
     $this->metadataFactory->addMetadata($metadata);
     $violations = $this->validate($entity, null, 'Default');
     /** @var ConstraintViolationInterface[] $violations */
     $this->assertCount(1, $violations);
     $this->assertSame('Violation in Group 2', $violations[0]->getMessage());
 }
Exemple #29
0
 /**
  * @param ClassMetadata $metadata
  */
 public static function loadValidatorMetadata(ClassMetadata $metadata)
 {
     $metadata->addPropertyConstraint('name', new NotBlank(array('message' => 'mautic.core.name.required')));
     $metadata->addConstraint(new Callback(array('callback' => function (Notification $notification, ExecutionContextInterface $context) {
         $type = $notification->getNotificationType();
         if ($type == 'list') {
             $validator = $context->getValidator();
             $violations = $validator->validate($notification->getLists(), array(new LeadListAccess(array('message' => 'mautic.lead.lists.required')), new NotBlank(array('message' => 'mautic.lead.lists.required'))));
             if (count($violations) > 0) {
                 $string = (string) $violations;
                 $context->buildViolation($string)->atPath('lists')->addViolation();
             }
         }
     })));
 }
Exemple #30
0
 /**
  * @param ClassMetadata $metadata
  */
 public static function loadValidatorMetadata(ClassMetadata $metadata)
 {
     $metadata->addPropertyConstraint('label', new Assert\NotBlank(array('message' => 'mautic.lead.field.label.notblank')));
     $metadata->addConstraint(new UniqueEntity(array('fields' => array('alias'), 'message' => 'mautic.lead.field.alias.unique')));
 }