php Symfony-Component-Validator-Validator-ValidatorInterface类(方法)实例源码

下面列出了php Symfony-Component-Validator-Validator-ValidatorInterface 类(方法)源码代码实例,从而了解它的用法。

作者:web3    项目:mincar   
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);
 }

作者:gobudgi    项目:gobudgi   
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);
 }

作者:surfne    项目:stepup-bundl   
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);
 }

作者:nejcpenk    项目:tactician-bundl   
public function testExecuteWithoutViolations()
 {
     $list = new ConstraintViolationList([]);
     $this->validator->shouldReceive('validate')->once()->andReturn($list);
     $this->middleware->execute(new FakeCommand(), function () {
     });
 }

作者:simgroe    项目:event-sourcin   
/**
  * @param mixed $command
  *
  * @return array
  */
 private function validateCommand($command)
 {
     if ($this->validator) {
         return $this->validator->validate($command);
     }
     return null;
 }

作者:johnarben246    项目:sampleffuf-cor   
/**
  * 
  * @param object $object
  * @throws ValidationException
  */
 public function validate($object)
 {
     $violations = $this->validator->validate($object);
     if (count($violations) > 0) {
         throw new ValidationException($violations);
     }
 }

作者:krzysztof-gzoch    项目:pay   
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));
 }

作者:ramunas    项目:platfor   
/**
  * @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])]);
 }

作者:microservices-playgroun    项目:api-comment   
/**
  * @param Validatable $comment
  *
  * @throws ValidationError
  * @return void
  */
 public function validate(Validatable $comment)
 {
     $errors = $this->validator->validate($comment);
     if ($errors->count()) {
         throw new ValidationError($errors);
     }
 }

作者:Nakar    项目:hexagonal_phoneboo   
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);
 }

作者:pinekt    项目:mysymfonysampl   
private function tryValidate(Article $article)
 {
     $errors = $this->validator->validate($article);
     if (count($errors)) {
         throw new \Exception(implode('\\n', $errors));
     }
 }

作者:alekitt    项目:param-fetcher-bundl   
/**
  * @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);
 }

作者:enhav    项目:enhav   
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();
             }
         }
     }
 }

作者:ramunas    项目:platfor   
/**
  * {@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);
     }
 }

作者:a2xchi    项目:pim-community-de   
/**
  * {@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;
 }

作者:teqneer    项目:ext-direc   
/**
  * {@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);
     }
 }

作者:pinekt    项目:mysymfonysampl   
private function tryValidate(Category $category)
 {
     $errors = $this->validator->validate($category);
     if (count($errors)) {
         throw new \Exception(implode('\\n', $errors));
     }
 }

作者:semplo    项目:mabe   
/**
  * @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;
 }

作者:josephjbrewe    项目:form-util   
/**
  * 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);
         }
     }
 }

作者:Nakar    项目:hexagonal_phoneboo   
/**
  * @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.');
     }
 }


问题


面经


文章

微信
公众号

扫码关注公众号