コード例 #1
0
 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);
 }
コード例 #2
0
 public function testExecuteWithoutViolations()
 {
     $list = new ConstraintViolationList([]);
     $this->validator->shouldReceive('validate')->once()->andReturn($list);
     $this->middleware->execute(new FakeCommand(), function () {
     });
 }
コード例 #3
0
 /**
  * @param mixed $command
  *
  * @return array
  */
 private function validateCommand($command)
 {
     if ($this->validator) {
         return $this->validator->validate($command);
     }
     return null;
 }
コード例 #4
0
 /**
  * 
  * @param object $object
  * @throws ValidationException
  */
 public function validate($object)
 {
     $violations = $this->validator->validate($object);
     if (count($violations) > 0) {
         throw new ValidationException($violations);
     }
 }
コード例 #5
0
 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));
 }
コード例 #6
0
ファイル: ValidatorSpec.php プロジェクト: web3d/mincart
 function it_does_not_validate_method_with_no_constraints(MethodInterface $method, ValidatorInterface $validator)
 {
     $constraints = [];
     $method->getValidationConstraints()->shouldBeCalled()->willReturn($constraints);
     $validator->validate([], $constraints)->shouldNotBeCalled();
     $this->validate($method);
 }
コード例 #7
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])]);
 }
コード例 #8
0
 /**
  * @param Validatable $comment
  *
  * @throws ValidationError
  * @return void
  */
 public function validate(Validatable $comment)
 {
     $errors = $this->validator->validate($comment);
     if ($errors->count()) {
         throw new ValidationError($errors);
     }
 }
コード例 #9
0
 public function testCreateUserWithDisabledValidationWillProceedImmediatelyToSave()
 {
     $user = $this->createExampleUser();
     $this->validatorMock->expects($this->never())->method('validate');
     $this->repositoryMock->expects($this->once())->method('save')->with($user);
     $this->useCase->createUser($user, false);
 }
コード例 #10
0
 private function tryValidate(Article $article)
 {
     $errors = $this->validator->validate($article);
     if (count($errors)) {
         throw new \Exception(implode('\\n', $errors));
     }
 }
コード例 #11
0
 /**
  * @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);
 }
コード例 #12
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();
             }
         }
     }
 }
コード例 #13
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if (empty($options['data_class'])) {
         return;
     }
     $className = $options['data_class'];
     if (!$this->doctrineHelper->isManageableEntity($className)) {
         return;
     }
     if (!$this->entityConfigProvider->hasConfig($className)) {
         return;
     }
     $uniqueKeys = $this->entityConfigProvider->getConfig($className)->get('unique_key');
     if (empty($uniqueKeys)) {
         return;
     }
     /* @var \Symfony\Component\Validator\Mapping\ClassMetadata $validatorMetadata */
     $validatorMetadata = $this->validator->getMetadataFor($className);
     foreach ($uniqueKeys['keys'] as $uniqueKey) {
         $fields = $uniqueKey['key'];
         $labels = array_map(function ($fieldName) use($className) {
             $label = $this->entityConfigProvider->getConfig($className, $fieldName)->get('label');
             return $this->translator->trans($label);
         }, $fields);
         $constraint = new UniqueEntity(['fields' => $fields, 'errorPath' => '', 'message' => $this->translator->transChoice('oro.entity.validation.unique_field', sizeof($fields), ['%field%' => implode(', ', $labels)])]);
         $validatorMetadata->addConstraint($constraint);
     }
 }
コード例 #14
0
 /**
  * {@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;
 }
コード例 #15
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);
     }
 }
コード例 #16
0
 private function tryValidate(Category $category)
 {
     $errors = $this->validator->validate($category);
     if (count($errors)) {
         throw new \Exception(implode('\\n', $errors));
     }
 }
コード例 #17
0
ファイル: EditMemberService.php プロジェクト: semplon/mabes
 /**
  * @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;
 }
コード例 #18
0
 /**
  * Merges constraints from the form with constraints in the class metaData
  *
  * @param FormInterface $form
  */
 public function mergeConstraints(FormInterface &$form)
 {
     $metaData = null;
     $dataClass = $form->getConfig()->getDataClass();
     if ($dataClass != '') {
         $metaData = $this->validator->getMetadataFor($dataClass);
     }
     if ($metaData instanceof ClassMetadata) {
         /**
          * @var FormInterface $child
          */
         foreach ($form->all() as $child) {
             $options = $child->getConfig()->getOptions();
             $name = $child->getConfig()->getName();
             $type = $child->getConfig()->getType()->getName();
             if (isset($options['constraints'])) {
                 $existingConstraints = $options['constraints'];
                 $extractedConstraints = $this->extractPropertyConstraints($name, $metaData);
                 // Merge all constraints
                 $options['constraints'] = array_merge($existingConstraints, $extractedConstraints);
             }
             $form->add($name, $type, $options);
         }
     }
 }
コード例 #19
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.');
     }
 }
コード例 #20
0
 /**
  * @param SourceInterface $source
  *
  * @throws ValidationException
  */
 protected function validate(SourceInterface $source)
 {
     $violations = $this->validator->validate($source);
     if ($violations->count()) {
         throw ValidationException::create($violations);
     }
 }
コード例 #21
0
 function it_validates_dto(ValidatorInterface $validator)
 {
     $createExpenseList = new CreateExpenseList();
     $createExpenseList->name = '';
     $validator->validate($createExpenseList)->willReturn(['field' => 'message']);
     $response = $this->createAction($createExpenseList);
     $response->getStatusCode()->shouldBe(400);
 }
コード例 #22
0
ファイル: PathFinder.php プロジェクト: Rastusik/ci-assignment
 /**
  * @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);
     }
 }
 public function testValidateDoesNotThrowExceptionIfThereAreNoErrors()
 {
     $errors = m::mock(ConstraintViolationListInterface::class);
     $errors->shouldReceive('count')->andReturn(0);
     $comment = m::mock(Validatable::class);
     $this->validator->shouldReceive('validate')->once()->andReturn($errors);
     $this->validationHandler->validate($comment);
 }
コード例 #24
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);
     }
 }
コード例 #26
0
 /**
  * @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;
 }
コード例 #27
0
 public function testAddNumberToUserValidationPassesWillProceedToSaveUser()
 {
     $number = $this->createExamplePhoneNumber();
     $this->repositoryMock->expects($this->once())->method('findById')->with(100)->will($this->returnValue($number));
     $this->validatorMock->expects($this->once())->method('validate')->with($number)->will($this->returnValue(new ConstraintViolationList()));
     $this->repositoryMock->expects($this->once())->method('save')->with($number);
     $this->useCase->editPhoneNumber($number);
 }
コード例 #28
0
ファイル: ViolationsMapper.php プロジェクト: mike227/n-forms
 /**
  * @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);
         }
     }
 }
コード例 #29
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());
     }
 }
コード例 #30
0
 /**
  * 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);
     }
 }