public function apply(Request $request, ParamConverter $configuration)
 {
     $name = $configuration->getName();
     $snakeCasedName = $this->camelCaseToSnakeCase($name);
     $class = $configuration->getClass();
     $json = $request->getContent();
     $object = json_decode($json, true);
     if (!isset($object[$snakeCasedName]) || !is_array($object[$snakeCasedName])) {
         throw new BadJsonRequestException([sprintf("Missing parameter '%s'", $name)]);
     }
     $object = $object[$snakeCasedName];
     $convertedObject = new $class();
     $errors = [];
     foreach ($object as $key => $value) {
         $properlyCasedKey = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
         if (!property_exists($convertedObject, $properlyCasedKey)) {
             $errors[] = sprintf("Unknown property '%s.%s'", $snakeCasedName, $key);
             continue;
         }
         $convertedObject->{$properlyCasedKey} = $value;
     }
     $violations = $this->validator->validate($convertedObject);
     if (count($errors) + count($violations) > 0) {
         throw BadJsonRequestException::createForViolationsAndErrors($violations, $name, $errors);
     }
     $request->attributes->set($name, $convertedObject);
 }
Exemplo n.º 2
0
 /**
  * @param SourceInterface $source
  *
  * @throws ValidationException
  */
 protected function validate(SourceInterface $source)
 {
     $violations = $this->validator->validate($source);
     if ($violations->count()) {
         throw ValidationException::create($violations);
     }
 }
Exemplo n.º 3
0
 /**
  * @param CommandInterface $command
  * @return bool
  */
 public function execute(CommandInterface $command)
 {
     if (!$command instanceof EditMemberCommand) {
         throw new \DomainException("Internal error, silahkan hubungi CS kami");
     }
     $command->setRepository($this->member_repo);
     $violation = $this->validator->validate($command);
     if ($violation->count() > 0) {
         $message = $violation->get(0)->getMessage();
         throw new \DomainException($message);
     }
     //        $member = new Member();
     $member = $this->app->em->getRepository("Mabes\\Entity\\Member")->find($command->getAccountId());
     $member->setEmail($command->getEmail());
     $member->setAccountNumber($command->getAccountNumber());
     $member->setAccountHolder($command->getAccountHolder());
     $member->setBankName($command->getBankName());
     $member->setFullName($command->getFullname());
     $member->setAddress($command->getAddress());
     $member->setPhone($command->getPhone());
     $this->app->em->flush();
     //        $this->member_repo->save($member);
     $data = ["account_id" => $member->getAccountId(), "email" => $member->getEmail(), "phone" => $member->getPhone(), "fullname" => $member->getFullName(), "bank_name" => $member->getBankName(), "account_number" => $member->getAccountNumber(), "account_holder" => $member->getAccountHolder(), "address" => $member->getAddress(), "date" => date("Y-m-d H:i:s")];
     $this->event_emitter->emit("validation.created", [$data]);
     return true;
 }
Exemplo n.º 4
0
 /**
  * @param User $user
  * @throws CreateUserException
  */
 private function validateUser(User $user)
 {
     $violations = $this->validator->validate($user);
     if ($violations->count()) {
         throw new CreateUserException($violations, 'Invalid User entity.');
     }
 }
 public function testValidationConfiguration()
 {
     $valid = $this->validator->validate(new ProductCollection([]));
     $this->assertCount(1, $valid);
     $productCollectionWithWrongProduct = new ProductCollection([new Product()]);
     $this->assertCount(3, $this->validator->validate($productCollectionWithWrongProduct));
 }
Exemplo n.º 6
0
 private function tryValidate(Category $category)
 {
     $errors = $this->validator->validate($category);
     if (count($errors)) {
         throw new \Exception(implode('\\n', $errors));
     }
 }
Exemplo n.º 7
0
 /**
  * 
  * @param object $object
  * @throws ValidationException
  */
 public function validate($object)
 {
     $violations = $this->validator->validate($object);
     if (count($violations) > 0) {
         throw new ValidationException($violations);
     }
 }
Exemplo n.º 8
0
 /**
  * {@inheritdoc}
  */
 public function validate(ServiceReference $service, array $arguments)
 {
     $validationResult = array();
     $parameterCount = 0;
     $validatedCount = 0;
     $hasStrictFailure = false;
     foreach ($arguments as $name => $value) {
         if (strpos($name, '__internal__') !== false) {
             continue;
         }
         $constraints = $service->getParameterConstraints($name);
         $validationGroups = $service->getParameterValidationGroups($name);
         $isStrictValidation = $service->isStrictParameterValidation($name);
         if (!empty($constraints)) {
             $violations = $this->validator->validate($value, $constraints, $validationGroups);
             if (count($violations)) {
                 $validationResult[$name] = $violations;
                 if ($isStrictValidation) {
                     $hasStrictFailure = true;
                 }
             }
             $validatedCount++;
         }
         $parameterCount++;
     }
     if ($this->strict && $parameterCount !== $validatedCount) {
         throw new StrictArgumentValidationException();
     }
     if (!empty($validationResult)) {
         throw new ArgumentValidationException(new ArgumentValidationResult($validationResult), $hasStrictFailure);
     }
 }
 /**
  * @inheritdoc
  */
 public function validate($value, Param $param)
 {
     $constraint = $this->getRequirementsConstraint($value, $param);
     if (null !== $constraint) {
         $constraint = [$constraint];
         if ($param->allowBlank === false) {
             $constraint[] = new NotBlank();
         }
         if ($param->nullable === false) {
             $constraint[] = new NotNull();
         }
     } else {
         $constraint = [];
     }
     if ($param->array) {
         $constraint = [new All(['constraints' => $constraint])];
     }
     if ($param->incompatibles) {
         $constraint[] = new IncompatibleParams($param->incompatibles);
     }
     if (!count($constraint)) {
         return new ConstraintViolationList();
     }
     return $this->validator->validate($value, $constraint);
 }
 /**
  * {@inheritdoc}
  */
 public function process($item)
 {
     $entity = $this->findOrCreateObject($item);
     try {
         $this->updater->update($entity, $item);
     } catch (\InvalidArgumentException $exception) {
         $this->skipItemWithMessage($item, $exception->getMessage(), $exception);
     }
     $violations = $this->validator->validate($entity);
     if ($violations->count() > 0) {
         $this->objectDetacher->detach($entity);
         $this->skipItemWithConstraintViolations($item, $violations);
     }
     $rawParameters = $entity->getRawParameters();
     if (!empty($rawParameters)) {
         $job = $this->jobRegistry->get($entity->getJobName());
         $parameters = $this->jobParamsFactory->create($job, $rawParameters);
         $violations = $this->jobParamsValidator->validate($job, $parameters);
         if ($violations->count() > 0) {
             $this->objectDetacher->detach($entity);
             $this->skipItemWithConstraintViolations($item, $violations);
         }
     }
     return $entity;
 }
Exemplo n.º 11
0
 /**
  * @param mixed $command
  *
  * @return array
  */
 private function validateCommand($command)
 {
     if ($this->validator) {
         return $this->validator->validate($command);
     }
     return null;
 }
Exemplo n.º 12
0
 /**
  * @param string          $dataClass Parent entity class name
  * @param File|Attachment $entity    File entity
  * @param string          $fieldName Field name where new file/image field was added
  *
  * @return \Symfony\Component\Validator\ConstraintViolationListInterface
  */
 public function validate($dataClass, $entity, $fieldName = '')
 {
     /** @var Config $entityAttachmentConfig */
     if ($fieldName === '') {
         $entityAttachmentConfig = $this->attachmentConfigProvider->getConfig($dataClass);
         $mimeTypes = $this->getMimeArray($entityAttachmentConfig->get('mimetypes'));
         if (!$mimeTypes) {
             $mimeTypes = array_merge($this->getMimeArray($this->config->get('oro_attachment.upload_file_mime_types')), $this->getMimeArray($this->config->get('oro_attachment.upload_image_mime_types')));
         }
     } else {
         $entityAttachmentConfig = $this->attachmentConfigProvider->getConfig($dataClass, $fieldName);
         /** @var FieldConfigId $fieldConfigId */
         $fieldConfigId = $entityAttachmentConfig->getId();
         if ($fieldConfigId->getFieldType() === 'file') {
             $configValue = 'upload_file_mime_types';
         } else {
             $configValue = 'upload_image_mime_types';
         }
         $mimeTypes = $this->getMimeArray($this->config->get('oro_attachment.' . $configValue));
     }
     $fileSize = $entityAttachmentConfig->get('maxsize') * 1024 * 1024;
     foreach ($mimeTypes as $id => $value) {
         $mimeTypes[$id] = trim($value);
     }
     return $this->validator->validate($entity->getFile(), [new FileConstraint(['maxSize' => $fileSize, 'mimeTypes' => $mimeTypes])]);
 }
 /**
  * @param Validatable $comment
  *
  * @throws ValidationError
  * @return void
  */
 public function validate(Validatable $comment)
 {
     $errors = $this->validator->validate($comment);
     if ($errors->count()) {
         throw new ValidationError($errors);
     }
 }
Exemplo n.º 14
0
 public function validate($value, Constraint $constraint)
 {
     if (!$value instanceof OrderInterface) {
         $this->context->buildViolation('Value should implements OrderInterface')->addViolation();
     }
     if ($value->getUser() === null) {
         $emailErrors = $this->validator->validate($value->getEmail(), [new NotNull(), new Email()]);
         foreach ($emailErrors as $error) {
             $this->context->buildViolation($error->getMessage())->addViolation();
         }
     }
     $shippingAddressErrors = $this->validator->validate($value->getShippingAddress());
     if (count($shippingAddressErrors)) {
         /** @var ConstraintViolation $error */
         foreach ($shippingAddressErrors as $error) {
             $this->context->buildViolation($error->getMessage())->addViolation();
         }
     }
     if ($value->isDifferentBillingAddress()) {
         $billingAddressErrors = $this->validator->validate($value->getBillingAddress());
         if (count($billingAddressErrors)) {
             /** @var ConstraintViolation $error */
             foreach ($billingAddressErrors as $error) {
                 $this->context->buildViolation($error->getMessage())->addViolation();
             }
         }
     }
 }
Exemplo n.º 15
0
 private function tryValidate(Article $article)
 {
     $errors = $this->validator->validate($article);
     if (count($errors)) {
         throw new \Exception(implode('\\n', $errors));
     }
 }
 /**
  * @param JobInterface  $job
  * @param JobParameters $jobParameters
  * @param array         $groups
  *
  * @return ConstraintViolationListInterface A list of constraint violations. If the
  *                                          list is empty, validation succeeded.
  */
 public function validate(JobInterface $job, JobParameters $jobParameters, $groups = null)
 {
     $provider = $this->registry->get($job);
     $collection = $provider->getConstraintCollection();
     $parameters = $jobParameters->all();
     $errors = $this->validator->validate($parameters, $collection, $groups);
     return $errors;
 }
Exemplo n.º 17
0
 private function doHandle(CommandMessageInterface $command)
 {
     $violations = $this->validator->validate($command->getPayload());
     if (0 !== $violations->count()) {
         throw new ValidatorException("One or more constraints were violated.", $violations);
     }
     return $command;
 }
 /**
  * @param $command
  */
 public function validate($command)
 {
     $violation = $this->validator->validate($command);
     if ($violation->count() > 0) {
         $message = str_replace("This value", ucfirst($violation->get(0)->getPropertyPath()), $violation->get(0)->getMessage());
         throw new InvalidCommandException($message);
     }
 }
Exemplo n.º 19
0
 /**
  * @param Queries $queries
  * @return void
  * @throws UnexpectedValueException
  */
 private function validateQueryies(Queries $queries)
 {
     $errors = $this->validator->validate($queries);
     if (count($errors) > 0) {
         $errorsString = (string) $errors;
         throw new UnexpectedValueException($errorsString);
     }
 }
Exemplo n.º 20
0
 /**
  * @param object $object
  * @param Container $container
  * @param array|NULL $controls
  * @param array|NULL $groups
  * @throws InvalidStateException
  */
 public function validateContainer($object, Container $container, array $controls = NULL, array $groups = NULL)
 {
     if ($object === NULL) {
         return;
     }
     $metadata = $this->classMetadataFactory->getMetadataFor(get_class($object));
     $parentContainer = $container;
     if ($groups === NULL) {
         while (TRUE) {
             if ($parentContainer instanceof IOptions) {
                 $groups = $parentContainer->getOption(ContainerBuilder::VALIDATION_GROUPS_OPTION);
                 break;
             }
             $parentContainer = $parentContainer->getParent();
             if (!$parentContainer) {
                 break;
             }
         }
     }
     $violations = $this->validator->validate($object, NULL, $groups);
     $this->mapViolationsToContainer($container, $violations, $controls);
     // Validate toOne subContainers
     foreach ($container->getComponents(FALSE, 'NForms\\ToOneContainer') as $subContainer) {
         /** @var ToOneContainer $subContainer */
         $fieldPath = $subContainer->getOption(IObjectMapper::FIELD_NAME, $subContainer->getName());
         if (!$metadata->hasAssociation($fieldPath)) {
             continue;
         }
         if (!$metadata->isSingleValuedAssociation($fieldPath)) {
             throw new InvalidStateException("ToMany association '{$metadata->getClass()}#{$fieldPath}' found but container is toOne.");
         }
         if ($metadata->hasField($fieldPath)) {
             $this->validateContainer($metadata->getFieldValue($object, $fieldPath), $subContainer, $controls);
         } elseif ($metadata->hasAssociation($fieldPath)) {
             $this->validateContainer($metadata->getAssociationValue($object, $fieldPath), $subContainer, $controls);
         }
     }
     // Validate toMany subContainers
     foreach ($container->getComponents(FALSE, 'NForms\\ToManyContainer') as $subContainer) {
         /** @var ToManyContainer $subContainer */
         $fieldPath = $subContainer->getOption(IObjectMapper::FIELD_NAME, $subContainer->getName());
         if (!$metadata->hasAssociation($fieldPath)) {
             continue;
         }
         if ($metadata->isSingleValuedAssociation($fieldPath)) {
             throw new InvalidStateException("ToOne association '{$metadata->getClass()}#{$fieldPath}' found but container is toMany.");
         }
         $collection = $metadata->getAssociationValue($object, $fieldPath);
         $containers = $subContainer->getComponents(FALSE, 'NForms\\ToOneContainer');
         foreach ($containers as $key => $toOneContainer) {
             /** @var ToOneContainer $toOneContainer */
             $this->validateContainer($collection[$key], $toOneContainer, $controls);
         }
         if ($metadata->hasField($fieldPath)) {
             $this->validateContainer($metadata->getFieldValue($object, $fieldPath), $subContainer, $controls);
         }
     }
 }
Exemplo n.º 21
0
 /**
  * @param $object
  * @param $groups
  * @return array|bool
  */
 public function validate($object, $groups = null)
 {
     $errors = $this->validator->validate($object, null, $groups);
     if (count($errors)) {
         return $this->toArray($errors);
     } else {
         return false;
     }
 }
Exemplo n.º 22
0
 /**
  * {@inheritdoc}
  */
 public function isValid(FormInterface $form)
 {
     $errors = $this->validator->validate($form->getModelData(), null, $form->getValidationGroups());
     if ($errors->count()) {
         $this->constraintViolationMapper->mapErrorsToForm($errors, $form);
         return false;
     }
     return true;
 }
 /**
  * Validate an object (Basic check).
  *
  * @param mixed $object the object to validate
  * @param bool|null|string|string[] $groups
  *
  * @throws ValidationFailedException
  */
 public static function validate($object, $groups = null)
 {
     static::initialize();
     $errors = static::$validator->validate($object, null, $groups);
     if ($errors->count() != 0) {
         //Throw new exception containing the errors
         throw new ValidationFailedException($errors, $object);
     }
 }
Exemplo n.º 24
0
 /**
  * @dataProvider provideTypeAndExpression
  * @param string      $expression
  * @param string|null $errorMessage
  */
 public function testWithTypeAndExpression($type, $expression, $errorMessage = null)
 {
     $errors = $this->validator->validate(static::createSchedule($type, $expression));
     $this->assertCount($errorMessage == null ? 0 : 1, $errors);
     if (null != $errorMessage) {
         $this->assertEquals('expression', $errors->get(0)->getPropertyPath());
         $this->assertEquals($errorMessage, $errors->get(0)->getMessage());
     }
 }
Exemplo n.º 25
0
 public function testValidationConfiguration()
 {
     $invalidOrderValidation = $this->validator->validate(new Order());
     $this->assertCount(6, $invalidOrderValidation);
     $validOrder = new Order();
     $validOrder->setCustomerIp('127.0.0.1')->setCurrencyCode('PLN')->setTotalAmount(new Money(10))->setDescription('Test')->setMerchantPosId('123')->setSignature('123');
     $validOrderValidation = $this->validator->validate($validOrder);
     $this->assertCount(0, $validOrderValidation);
 }
 /**
  * {@inheritdoc}
  */
 public function validate($entity, array $columnsInfo, array $data, array $errors = [])
 {
     $this->checkIdentifier($entity, $columnsInfo, $data);
     if (!count($errors)) {
         return $this->getErrorMap($this->validator->validate($entity));
     } else {
         return $this->validateProperties($entity, $columnsInfo) + $errors;
     }
 }
Exemplo n.º 27
0
 protected function validateEntity($entity)
 {
     $violations = $this->validator->validate($entity);
     if ($violations->count() === 0) {
         return;
     }
     // taken from UnitOfWork::objToStr()
     $entityIdentifier = method_exists($entity, '__toString') ? (string) $entity : get_class($entity) . '@' . spl_object_hash($entity);
     throw new EntityValidationException('Entity ' . $entityIdentifier . ' is not valid: ' . $violations);
 }
Exemplo n.º 28
0
 public function subscribeNewsletter()
 {
     $errors = $this->validator->validate($this->blaster);
     if (count($errors) > 0) {
         //some errors found, log the errors
         $this->logger->addError((string) $errors);
     }
     $this->em->persist($this->blaster);
     $this->em->flush();
 }
Exemplo n.º 29
0
 /**
  * @param PhoneNumber $number
  * @param User $user
  * @throws NotExistingUserException
  * @throws AddNumberToUserException
  */
 private function validateInput(PhoneNumber $number, User $user)
 {
     if (!$this->userRepository->findById($user->getId())) {
         throw new NotExistingUserException(sprintf('User with [id = %d] does not exist', $user->getId()));
     }
     $violations = $this->validator->validate($number);
     if ($violations->count()) {
         throw new AddNumberToUserException($violations);
     }
 }
Exemplo n.º 30
0
 /**
  * @param User $user
  * @throws EditUserException
  *
  */
 private function validateUser(User $user)
 {
     if (!$this->repository->findById($user->getId())) {
         throw new NotExistingUserException(sprintf('User with [id = %d] does not exist', $user->getId()));
     }
     $violations = $this->validator->validate($user);
     if ($violations->count()) {
         throw new EditUserException($violations, 'Invalid User entity.');
     }
 }