/**
  * @test
  * @expectedException \InvalidArgumentException
  * @expectedExceptionMessage Not all properties set correctly
  */
 public function thatPutInThrowsValidatorException()
 {
     $reflection = new \ReflectionMethod('Diamante\\ApiBundle\\Tests\\Handler\\Fixtures\\Object', 'getParts');
     $dummyBagFirst = new ParameterBag(['id' => '1']);
     $this->validator->expects($this->once())->method('validate')->will($this->returnValue(new ConstraintViolationList([new ConstraintViolation('Not all properties set correctly', 'Not all properties set correctly', [], '', '', '')])));
     $methodParameters = new MethodParameters($reflection, $this->validator);
     $methodParameters->putIn($dummyBagFirst);
 }
예제 #2
0
 /**
  * Helper method to set data to specified entity and store it to database.
  *
  * @todo    should this throw an error, if given data contains something else than entity itself?
  * @todo    should this throw an error, if setter method doesn't exists?
  *
  * @throws  ValidatorException
  *
  * @param   Entity      $entity
  * @param   \stdClass   $data
  *
  * @return  void
  */
 protected function persistEntity(Entity $entity, \stdClass $data)
 {
     // Specify properties that are not allowed to update by user
     $ignoreProperties = ['createdAt', 'createdBy', 'updatedAt', 'updatedBy'];
     // Iterate given data
     foreach ($data as $property => $value) {
         if (in_array($property, $ignoreProperties)) {
             continue;
         }
         // Specify setter method for current property
         $method = sprintf('set%s', ucwords($property));
         // Yeah method exists, so use it with current value
         if (method_exists($entity, $method)) {
             $entity->{$method}($value);
         }
     }
     // Validate entity
     $errors = $this->validator->validate($entity);
     // Oh noes, we have some errors
     if (count($errors) > 0) {
         throw new ValidatorException($errors);
     }
     // And make entity persist on database
     $this->entityManager->persist($entity);
     $this->entityManager->flush($entity);
 }
예제 #3
0
 /**
  * Validate if the Alias is valid and unique.
  *
  * @param FormEvent $event
  */
 public function validate(FormEvent $event)
 {
     /** @var Alias $alias */
     $alias = $event->getData()->getNode()->alias;
     if ($alias instanceof ValueHolderInterface) {
         $alias = $alias->getWrappedValueHolderValue();
     }
     $violations = $this->validator->validate($alias);
     if (!$violations) {
         return;
     }
     $mapper = new ViolationMapper();
     /** @var ConstraintViolationInterface $violation */
     foreach ($violations as $violation) {
         $mapper->mapViolation($violation, $event->getForm(), true);
     }
 }
 /**
  * Entity validation
  *
  * @param CrudEntityInterface $entity Entity
  * @return ConstraintViolationList|bool
  */
 public function validate(CrudEntityInterface $entity)
 {
     $violations = $this->validator->validate($entity);
     if ($violations->count()) {
         return $violations;
     }
     return true;
 }
예제 #5
0
 /**
  * Return if email is valid.
  *
  * @param string $email Email
  *
  * @return bool Email is valid
  */
 public function validateEmail($email)
 {
     if (empty($email)) {
         return false;
     }
     $validationViolationList = $this->validator->validate($email, new Email());
     return $validationViolationList->count() === 0;
 }
 /**
  * Stores the object in the request.
  *
  * @param Request        $request       The request
  * @param ParamConverter $configuration Contains the name, class and options of the object
  *
  * @throws \InvalidArgumentException
  *
  * @return bool True if the object has been successfully set, else false
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $name = $configuration->getName();
     $class = $configuration->getClass();
     $options = $configuration->getOptions();
     if (isset($options['query'])) {
         $content = new \stdClass();
         $metadata = $this->serializer->getMetadataFactory()->getMetadataForClass($class);
         foreach ($metadata->propertyMetadata as $propertyMetadata) {
             if (!$propertyMetadata->readOnly) {
                 $property = $propertyMetadata->name;
                 $value = $request->query->get($propertyMetadata->name);
                 if (!is_null($value)) {
                     $content->{$property} = $request->query->get($propertyMetadata->name);
                 }
             }
         }
         $content = json_encode($content);
     } else {
         $content = $request->getContent();
     }
     if (!class_exists($class)) {
         throw new \InvalidArgumentException($class . ' class does not exist.');
     }
     $success = false;
     try {
         $model = $this->serializer->deserialize($content, $class, 'json');
         $success = true;
     } catch (\Exception $e) {
         $model = new $class();
     }
     /**
      * Validate if possible
      */
     if ($model instanceof ValidatableInterface) {
         $violations = $this->validator->validate($model);
         $valid = $success && !(bool) $violations->count();
         $model->setViolations($violations);
         $model->setValid($valid);
     }
     /**
      * Adding transformed collection
      * to request attribute.
      */
     $request->attributes->set($name, $model);
     /**
      * Alias to access current collection
      * Used by exception listener
      */
     $request->attributes->set(Alias::DATA, $name);
     return true;
 }
예제 #7
0
 /**
  * Validate
  *
  * @param array $input
  * @return boolean
  */
 public function validate($input)
 {
     $this->dataInput = $input;
     $this->errorList = array();
     //Get Validation collection
     $collections = $this->getValidatorCollection();
     if (empty($collections)) {
         return true;
     }
     //Create constraint
     $constraintCollection = array('fields' => $collections, 'allowExtraFields' => $this->allowExtraFields);
     if ($this->extraFieldsMessage !== '') {
         $constraintCollection['extraFieldsMessage'] = $this->extraFieldsMessage;
     }
     if ($this->missingFieldsMessage !== '') {
         $constraintCollection['missingFieldsMessage'] = $this->missingFieldsMessage;
     }
     $constraint = new Collection($constraintCollection);
     //Validate
     $validatorResult = $this->validator->validate($input, $constraint);
     //Parse error
     $this->parseError($validatorResult);
     return count($this->errorList) === 0;
 }
 public function validate(FormEvent &$event, $contentObject)
 {
     /** @var $layoutBlock LayoutBlockInterface */
     $form = $event->getForm();
     /** @var \Symfony\Component\Validator\ConstraintViolationList $errors */
     $errors = $this->validator->validate($contentObject);
     if (count($errors) > 0) {
         if ($contentObject->getId()) {
             $message = $this->admin->getTranslator()->trans('message.layout_block_not_edited', array(), $this->admin->getTranslationDomain());
         } else {
             $message = $this->admin->getTranslator()->trans('message.layout_block_not_created', array(), $this->admin->getTranslationDomain());
         }
         $form->addError(new FormError($message));
         /** @var \Symfony\Component\Validator\ConstraintViolation $error */
         foreach ($errors->getIterator() as $error) {
             $fieldName = $error->getPropertyPath();
             /** @var \Symfony\Component\Form\Form $field */
             $field = $form->get('content')->get($fieldName);
             $field->addError(new FormError($error->getMessage(), $error->getMessageTemplate(), $error->getMessageParameters(), $error->getMessagePluralization()));
         }
     }
     return $event;
 }
예제 #9
0
 public function validateValue($value, $constraints, $groups = null)
 {
     trigger_error('The ' . __METHOD__ . ' method is deprecated in version 2.5 and will be removed in version 3.0. Use the Symfony\\Component\\Validator\\Validator\\ValidatorInterface::validate method instead.', E_USER_DEPRECATED);
     return parent::validate($value, $constraints, $groups);
 }
예제 #10
0
 /**
  * @param array $data
  * @return bool
  */
 public function isNewCommentValid(array $data)
 {
     $constraint = new Assert\Collection(['topic' => [new Assert\Type(['type' => 'int']), new Assert\NotBlank()], 'content' => [new Assert\NotBlank()]]);
     $this->lastErrors = $this->validator->validateValue($data, $constraint);
     return 0 === count($this->lastErrors);
 }
예제 #11
0
 /**
  * Validates the object and all objects related to this table.
  *
  * @see        getValidationFailures()
  * @param      ValidatorInterface|null $validator A Validator class instance
  * @return     boolean Whether all objects pass validation.
  */
 public function validate(ValidatorInterface $validator = null)
 {
     if (null === $validator) {
         $validator = new RecursiveValidator(new ExecutionContextFactory(new IdentityTranslator()), new LazyLoadingMetadataFactory(new StaticMethodLoader()), new ConstraintValidatorFactory());
     }
     $failureMap = new ConstraintViolationList();
     if (!$this->alreadyInValidation) {
         $this->alreadyInValidation = true;
         $retval = null;
         $retval = $validator->validate($this);
         if (count($retval) > 0) {
             $failureMap->addAll($retval);
         }
         if (null !== $this->collPermissionGroupUsers) {
             foreach ($this->collPermissionGroupUsers as $referrerFK) {
                 if (method_exists($referrerFK, 'validate')) {
                     if (!$referrerFK->validate($validator)) {
                         $failureMap->addAll($referrerFK->getValidationFailures());
                     }
                 }
             }
         }
         if (null !== $this->collLyrics) {
             foreach ($this->collLyrics as $referrerFK) {
                 if (method_exists($referrerFK, 'validate')) {
                     if (!$referrerFK->validate($validator)) {
                         $failureMap->addAll($referrerFK->getValidationFailures());
                     }
                 }
             }
         }
         if (null !== $this->collLyricTranslations) {
             foreach ($this->collLyricTranslations as $referrerFK) {
                 if (method_exists($referrerFK, 'validate')) {
                     if (!$referrerFK->validate($validator)) {
                         $failureMap->addAll($referrerFK->getValidationFailures());
                     }
                 }
             }
         }
         if (null !== $this->collLyricVotes) {
             foreach ($this->collLyricVotes as $referrerFK) {
                 if (method_exists($referrerFK, 'validate')) {
                     if (!$referrerFK->validate($validator)) {
                         $failureMap->addAll($referrerFK->getValidationFailures());
                     }
                 }
             }
         }
         if (null !== $this->collArtists) {
             foreach ($this->collArtists as $referrerFK) {
                 if (method_exists($referrerFK, 'validate')) {
                     if (!$referrerFK->validate($validator)) {
                         $failureMap->addAll($referrerFK->getValidationFailures());
                     }
                 }
             }
         }
         if (null !== $this->collAlbums) {
             foreach ($this->collAlbums as $referrerFK) {
                 if (method_exists($referrerFK, 'validate')) {
                     if (!$referrerFK->validate($validator)) {
                         $failureMap->addAll($referrerFK->getValidationFailures());
                     }
                 }
             }
         }
         $this->alreadyInValidation = false;
     }
     $this->validationFailures = $failureMap;
     return (bool) (!(count($this->validationFailures) > 0));
 }
예제 #12
0
 public function validateValue($value, $constraints, $groups = null)
 {
     return parent::validate($value, $constraints, $groups);
 }
예제 #13
0
 /**
  * Checks new topic data is valid
  *
  * Also updates $lastErrors property with any errors (or none)
  *
  * @param array $data
  *
  * @return bool
  */
 public function isNewTopicValid(array $data)
 {
     $constraint = new Assert\Collection(['title' => [new Assert\Length(['max' => 120]), new Assert\NotBlank()], 'excerpt' => [new Assert\Length(['max' => 255]), new Assert\NotBlank()], 'details' => [new Assert\NotBlank()], 'owned_by_creator' => [new Assert\Type(['type' => 'bool']), new Assert\NotBlank()]]);
     $this->lastErrors = $this->validator->validateValue($data, $constraint);
     return 0 === count($this->lastErrors);
 }