/** * Validate an associative array using the constraints defined in * getConstraints() and getOptionalConstraints(). * * All constraints from getConstraints() are used. * * Constraints from getOptionalConstraints() are only used if the field exists in $values. * * @param array $values Values to validate * @param AbstractEntity $contextEntity The existing entity to which the validated values * will be applied. Optional. * @return ConstraintViolationList */ public function validate(array $values, AbstractEntity $contextEntity = null) { $this->contextData = $values; $constraints = $this->getConstraints($values, $contextEntity); $arrayConstraint = new Assert\Collection(['fields' => $constraints, 'missingFieldsMessage' => self::MISSING]); return $this->validator->validateValue($values, $arrayConstraint); }
/** * 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()); }
/** * @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->validateValue($entity->getFile(), [new FileConstraint(['maxSize' => $fileSize, 'mimeTypes' => $mimeTypes, 'mimeTypesMessage' => 'This file type is not allowed.'])]); }
/** * Factory an implementation adding it to container builder * after being validated in structure (not connection) of * each server data * * @param string $implementation * @param array $configuration * @param ContainerBuilder $containerBuilder * @throws BadConfigurationException */ public function factoryImplementationConfiguration($implementation, array $configuration, ContainerBuilder $containerBuilder) { $serversToStore = array(); if (!in_array($implementation, UrodozCacheExtension::$availableImplementations)) { throw new BadConfigurationException("The implementation {" . $implementation . "} is not supported by the bundle UrodozCacheManager"); } $implementationConfigs = static::$implementationsConfigs[$implementation]; $validationStoreClass = $implementationConfigs["validationStoreClass"]; $servers = $configuration[$implementation]["servers"]; foreach ($servers as $serverString) { $explodedServerString = explode(":", $serverString); if (count($explodedServerString) != 2) { throw new BadConfigurationException("Expected {host}:{port} on server definition, got : " . $serverString); } //Create the store and validates it $storeValidator = new $validationStoreClass($explodedServerString[0], (int) $explodedServerString[1]); $violationCollection = $this->validator->validate($storeValidator); if (count($violationCollection) != 0) { throw new BadConfigurationException("Error on server definition : " . $serverString . ". " . $violationCollection[0]->getMessage() . " at property {" . $violationCollection[0]->getPropertyPath() . "}"); } //Store the server definition on the array to inject on the container $serversToStore[] = array("host" => $explodedServerString[0], "port" => (int) $explodedServerString[1]); } //Store the response on the container $containerBuilder->setParameter($implementationConfigs["parameterKey"], $serversToStore); }
public function loadUserByUsername($username) { $user = $this->findUserByFbId($username); try { $fbdata = $this->facebook->api('/me'); } catch (FacebookApiException $e) { $fbdata = null; } if (!empty($fbdata)) { if (empty($user)) { $user = $this->userManager->createUser(); $user->setEnabled(true); $user->setPassword(''); } // TODO use http://developers.facebook.com/docs/api/realtime $user->setFBData($fbdata); if (count($this->validator->validate($user, 'Facebook'))) { // TODO: the user was found obviously, but doesnt match our expectations, do something smart throw new UsernameNotFoundException('The facebook user could not be stored'); } $this->userManager->updateUser($user); } if (empty($user)) { throw new UsernameNotFoundException('The user is not authenticated on facebook'); } return $user; }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { if (empty($options['data_class'])) { return; } $className = $options['data_class']; if (!$this->entityConfigProvider->hasConfig($className)) { return; } $config = $this->entityConfigProvider->getConfig($className); if (!$config->has('unique_key')) { return; } $uniqueKeys = $config->get('unique_key', false, ['keys' => []]); /* @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); } }
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); }
public function testGetMetadataFactory() { $this->assertInstanceOf( 'Symfony\Component\Validator\MetadataFactoryInterface', $this->validator->getMetadataFactory() ); }
public function testActivityRequiredFieldsOnly() { $activityData = array('id' => 'http://inkstand.org/xapi/test/1234'); $activity = $this->activityService->denormalize(json_encode($activityData)); $constraintViolationList = $this->validator->validate($activity); $this->assertEquals($constraintViolationList->count(), 0); }
/** * validates user * @param \Symfony\Component\Security\Core\User\UserInterface $user * @throws \Symfony\Component\Security\Core\Exception\UsernameNotFoundException */ protected function validate(UserInterface $user) { // check without validator groups if (count($this->validator->validate($user))) { throw new UsernameNotFoundException('The social media user could not be stored'); } }
public function testExecuteWithInvalidEmail() { $this->setExpectedException('\\Symfony\\Component\\Validator\\Exception\\ValidatorException', 'test'); $options = ['from' => 'invalidemailaddress', 'to' => '*****@*****.**', 'template' => 'test', 'subject' => 'subject', 'body' => 'body', 'entity' => new \stdClass()]; $context = []; $this->contextAccessor->expects($this->any())->method('getValue')->will($this->returnArgument(1)); $this->entityNameResolver->expects($this->any())->method('getName')->will($this->returnCallback(function () { return '_Formatted'; })); $violationList = $this->getMockBuilder('Symfony\\Component\\Validator\\ConstraintViolationList')->disableOriginalConstructor()->getMock(); $violationList->expects($this->once())->method('count')->willReturn(1); $violationListInterface = $this->getMockBuilder('Symfony\\Component\\Validator\\ConstraintViolationInterface')->disableOriginalConstructor()->getMock(); $violationListInterface->expects($this->once())->method('getMessage')->willReturn('test'); $violationList->expects($this->once())->method('get')->willReturn($violationListInterface); $this->validator->expects($this->once())->method('validate')->willReturn($violationList); $this->objectRepository->expects($this->never())->method('findByName')->with($options['template'])->willReturn($this->emailTemplate); $this->emailTemplate->expects($this->never())->method('getType')->willReturn('txt'); $this->renderer->expects($this->never())->method('compileMessage')->willReturn([$options['subject'], $options['body']]); $emailEntity = $this->getMockBuilder('\\Oro\\Bundle\\EmailBundle\\Entity\\Email')->disableOriginalConstructor()->getMock(); $this->emailProcessor->expects($this->never())->method('process'); if (array_key_exists('attribute', $options)) { $this->contextAccessor->expects($this->once())->method('setValue')->with($context, $options['attribute'], $emailEntity); } $this->action->initialize($options); $this->action->execute($context); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $this->formatOutput($output); $this->getDependencies(); $latitude = $input->getOption('latitude'); $longitude = $input->getOption('longitude'); $radius = $input->getOption('radius'); $city = $input->getOption('city'); if (!$city && !($latitude && $longitude)) { return $output->writeln('<error>Insert city parameter or latitude + longitude.</error>'); } if ($city) { $geocodedAddress = $this->geocoder->geocode($city); $latitude = $geocodedAddress->getLat(); $longitude = $geocodedAddress->getLng(); } $restaurants = array(); $nextPage = null; do { $output->writeln('Searching in google place'); $placeResults = $this->googlePlaceClient->search($latitude, $longitude, null, $radius, $nextPage); $nextPage = $placeResults->getNextPage(); foreach ($placeResults->toArray() as $placeResult) { $restaurant = new Restaurant(); $fullPlaceResult = $this->googlePlaceClient->detail($placeResult->getId()); $restaurant->setName($placeResult->getName()); $restaurant->setLat($fullPlaceResult->getLatitude()); $restaurant->setLng($fullPlaceResult->getLongitude()); $restaurant->setAddress($fullPlaceResult->getFormattedAddress()); $address = new Address(); $address->setCity($fullPlaceResult->getCity()); $address->setLat($fullPlaceResult->getLatitude()); $address->setLng($fullPlaceResult->getLongitude()); $address->setFormattedAddress($fullPlaceResult->getFormattedAddress()); $this->addressManager->hydrateGeoname($address); $restaurant->setGeoname($address->getGeoname()); $photosReferences = $fullPlaceResult->getPhotoReferences(); if (count($photosReferences) > 0) { $message = $this->googlePlaceClient->image($photosReferences[0]); $imageContent = $message->getContent(); $filename = $this->s3->uploadData($imageContent, 'restaurant/'); $restaurant->setPicture($filename); } $errors = $this->validator->validate($restaurant); if (count($errors) > 0) { $output->writeln(sprintf('<error>Import error:</error> %s ', (string) $errors)); } else { $restaurants[] = $restaurant; $this->entityManager->persist($restaurant); $output->writeln(sprintf('Imported: <info>%s</info> - %s', $restaurant->getName(), $address->getFormattedAddress())); } } } while ($nextPage); $this->entityManager->flush(); $output->writeln(sprintf('<success>Imported successfully %d Restaurants</success>', count($restaurants))); }
/** * Validates the contents of the Descriptor and outputs warnings and error if something is amiss. * * @param DescriptorAbstract $descriptor * * @return Collection */ public function validate($descriptor) { $violations = $this->validator->validate($descriptor); $errors = new Collection(); /** @var ConstraintViolation $violation */ foreach ($violations as $violation) { $errors->add(new Error($this->mapCodeToSeverity($violation->getCode()), $violation->getMessageTemplate(), $descriptor->getLine(), $violation->getMessageParameters() + array($descriptor->getFullyQualifiedStructuralElementName()))); } return $errors; }
/** * Validated this Entity according to the rules specified in self::loadValidatorMetadata * * @param null $groups * * @throws InvalidEntity * @throws Exception * * @return ConstraintViolationList */ public function validate($groups = null) { if (!$this->validator) { throw new Exception('Cannot validate Entity, no validator present!'); } $violations = $this->validator->validate($this, $groups); if (count($violations) > 0) { throw new InvalidEntity($violations); } return $violations; }
/** * @param string $email * * @throws \Symfony\Component\Validator\Exception\ValidatorException */ protected function validateAddress($email) { $emailConstraint = new EmailConstraints(); $emailConstraint->message = 'Invalid email address'; if ($email) { $errorList = $this->validator->validateValue($email, $emailConstraint); if ($errorList && $errorList->count() > 0) { throw new ValidatorException($errorList->get(0)->getMessage()); } } }
/** * This method checks whether all required parameters exist in the given * PaymentInstruction, and whether they are syntactically correct. * * This method is meant to perform a fast parameter validation; no connection * to any payment back-end system should be made at this stage. * * In case, this method is not implemented. The PaymentInstruction will * be considered to be valid. * * @param PaymentInstructionInterface $instruction * * @throws \JMS\Payment\CoreBundle\Plugin\Exception\InvalidPaymentInstructionException if the the PaymentInstruction is not valid */ public function checkPaymentInstruction(PaymentInstructionInterface $instruction) { // define form validators $constraints = new Assert\Collection(array('name' => array(new Assert\NotBlank(array('message' => 'Required'))), 'number' => array(new Assert\NotBlank(array('message' => 'Required')), new Assert\Length(array('min' => 12, 'max' => 19, 'minMessage' => 'Invalid card number 1', 'maxMessage' => 'Invalid card number 2')), new Assert\Luhn(array('message' => 'Invalid card number'))), 'exp_month' => array(new Assert\NotBlank(array('message' => 'Required')), new Assert\Range(array('min' => 1, 'max' => 12, 'minMessage' => 'Invalid code value', 'maxMessage' => 'Invalid code value'))), 'exp_year' => array(new Assert\NotBlank(array('message' => 'Required')), new Assert\Range(array('min' => date('Y'), 'max' => date('Y', strtotime('+20 years')), 'minMessage' => 'Invalid date', 'maxMessage' => 'Invalid date'))), 'cvc' => array(new Assert\NotBlank(array('message' => 'Required')), new Assert\Length(array('min' => 3, 'max' => 4, 'minMessage' => 'Invalid code value', 'maxMessage' => 'Invalid code value'))), 'address_line1' => array(new Assert\NotBlank(array('message' => 'Required'))), 'address_line2' => array(), 'address_city' => array(new Assert\NotBlank(array('message' => 'Required'))), 'address_state' => array(new Assert\NotBlank(array('message' => 'Required'))), 'address_country' => array(new Assert\NotBlank(array('message' => 'Required'))), 'address_zip' => array(new Assert\NotBlank(array('message' => 'Required'))))); // extract form values from extended data $dateToValidate = array(); foreach ($constraints->fields as $name => $constraint) { $dateToValidate[$name] = $instruction->getExtendedData()->get($name); } // validate input data $errors = $this->validator->validateValue($dateToValidate, $constraints); // transform validator errors into payment exceptions $errorBuilder = new ErrorBuilder(); foreach ($errors as $error) { // KLUDGE: remove [] around field name $field = substr($error->getPropertyPath(), 1, -1); $errorBuilder->addDataError('data_stripe_credit_card.' . $field, $error->getMessage()); } if ($errorBuilder->hasErrors()) { throw $errorBuilder->getException(); } }
public function loadUserByOAuthUserResponse(UserResponseInterface $response) { $socialID = $response->getUsername(); /** @var User $user */ $user = $this->userManager->loadUser(['facebookId' => $socialID]); $update = true; $email = $response->getEmail(); //check if the user already has the corresponding social account if (null === $user) { //check if the user has a normal account $user = $this->userManager->loadUser($email, 'email'); if (null === $user || !$user instanceof UserInterface) { //if the user does not have a normal account, set it up: /** @var User $user */ $name = $response->getNickname() ?? $response->getRealName(); $user = $this->userManager->createUser($name, md5(uniqid()), $response->getEmail(), ['ROLE_OAUTH_USER']); $user->setEmail($email); $user->setFullName($name); $user->setEnabled(true); $violations = $this->validator->validate($user); $update = !$violations->count() === 0; if ($violations->count() === 0) { $this->session->getFlashBag()->add('warning', 'Welcome! You must complete your profile in order to use the features on the site.'); } else { throw new CustomUserMessageAuthenticationException('An account in your name already exists.'); } } if ($update) { //then set its corresponding social id $service = $response->getResourceOwner()->getName(); switch ($service) { case 'google': $user->setGoogleID($socialID); break; case 'facebook': $user->setFacebookID($socialID); break; } $this->userManager->updateUser($user); } } else { //and then login the user $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $this->tokenStorage->setToken($token); } $user->setLastLoggedIn(new \DateTime()); $this->userManager->updateUser($user); return $user; }
/** * @return RestResponse */ public function run() { $this->checkIsInit(); try { if (!$this->isEntityExists($this->entityId)) { return (new RestResponse(false))->setStatusCode(RestResponse::STATUS_CODE_ENTITY_NOT_FOUND)->setMessage("Сущность {$this->className} с id={$this->entityId} не была найдена"); } $requestContentAsObj = $this->convertRequestDataToObj($this->requestContent); $entity = $this->mergeDataFromRequestWithEntity($requestContentAsObj); /** @var ConstraintViolationList $validations */ $validations = $this->validator->validate($entity); if ($validations->count() !== 0) { return (new RestResponse(false))->setStatusCode(RestResponse::STATUS_CODE_WRONG_INPUT_DATA)->setErrors($validations); } $entity = $this->em->merge($entity); $this->em->flush(); if ($this->newPrimaryKeyValue !== null) { EntityHelper::changePKValueAndSave($this->em, $entity, $this->newPrimaryKeyValue); } return (new RestResponse(true))->setStatusCode(RestResponse::STATUS_CODE_OK)->setData($entity); } catch (\Exception $e) { return (new RestResponse(false))->setStatusCode(RestResponse::STATUS_CODE_WRONG_INPUT_DATA)->setMessage($e->getMessage()); } }
private function createUser() { $this->testIfEmailAlreadyInUse(); $this->testIfUsernameAlreadyInUse(); $this->populateUserWithSubmitedDatas(); $modelErrors = $this->sfValidator->validate($this->newUser); if (count($modelErrors)) { throw new \Exception(json_encode($modelErrors), 400); } // $this->dispatcher->dispatch(SfynxCmfEvents::REGISTRATION_WS_SUCCESS, new UserEvent($this->newUser, $this->request)); // $this->userManager->updateUser($this->newUser); if ($this->mailer) { $this->mailer->sendConfirmationEmailMessage($this->newUser); } }
/** * @param \Symfony\Component\HttpFoundation\Request $request * @param \Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter $configuration * @return bool * @throws \Exception */ public function apply(Request $request, ParamConverter $configuration) { $class = $configuration->getClass(); $options = $this->getOptions($configuration); switch ($request->getMethod()) { case 'GET': $data = $this->buildModelFromGetRequest($request, $configuration, $options); break; case 'PATCH': $data = $this->buildModelFromPatchRequest($request, $configuration, $options); break; case 'POST': $data = $this->buildModelFromPostRequest($request, $configuration, $options); break; case 'DELETE': $data = $this->buildModelFromDeleteRequest($request, $configuration, $options); break; default: $data = $request->getContent(); } $object = null; if ((!empty($data) || false === $configuration->isOptional()) && $request->headers->get('Content-Type') != 'application/octet-stream') { $object = $this->serializer->deserialize($data, $class, $options['format']); } if (null === $object && false === $configuration->isOptional()) { throw new NotFoundHttpException(sprintf('%s object not found.', $class)); } if (null !== $object) { if ($this->filterer) { $this->filterer->apply($object); } $constraintViolations = $this->validator->validate($object); if ($constraintViolations->count()) { throw new ConstraintViolationException($constraintViolations); } } $request->attributes->set($configuration->getName(), $object); return true; }
/** * @param Request $request * @return array|RedirectResponse * * @Extra\Template("WeavingTheWebUserBundle:Settings:show.html.twig") */ public function saveAction(Request $request) { $currentUser = $this->getUser(); $form = $this->getSettingsForm($currentUser); $form->handleRequest($request); if ($request->getMethod() === 'POST') { if ($form->isValid()) { $currentPassword = $form->get('currentPassword')->getData(); $errorList = $this->validator->validateValue($currentPassword, new UserPassword()); if (count($errorList) === 0) { $plainPassword = $form->get('plainPassword')->getData(); if (strlen(trim($plainPassword)) === 0) { $currentUser->setPlainPassword($currentPassword); } $this->userManager->updateUser($currentUser); return new RedirectResponse($this->router->generate('weaving_the_web_user_show_settings')); } else { $currentPasswordError = $this->translator->trans('field_error_current_password', [], 'user'); $form->get('currentPassword')->addError(new FormError($currentPasswordError)); } } } return ['form' => $form->createView()]; }
/** * Tests model validation */ public function testModel() { $model = new SofortPaymentRequestModel(); $errors = $this->validator->validate($model); $this->assertTrue($this->hasError('amount', $errors)); $this->assertTrue($this->hasError('reason', $errors)); // test amount $model->setAmount(-2); $errors = $this->validator->validate($model); $this->assertTrue($this->hasError('amount', $errors)); $model->setAmount(10); $errors = $this->validator->validate($model); $this->assertFalse($this->hasError('amount', $errors)); // test account number $model->setAccountNumber('88888888'); $errors = $this->validator->validate($model); $this->assertFalse($this->hasError('accountNumber', $errors)); // test bank code $model->setBankCode('12345678'); $errors = $this->validator->validate($model); $this->assertFalse($this->hasError('bankCode', $errors)); // test name $model->setName('Max Mustermann'); $errors = $this->validator->validate($model); $this->assertFalse($this->hasError('name', $errors)); // test country $model->setCountry('AAAA'); $errors = $this->validator->validate($model); $this->assertTrue($this->hasError('country', $errors)); $model->setCountry('DE'); $errors = $this->validator->validate($model); $this->assertFalse($this->hasError('country', $errors)); // test reason $model->setReason('test reason'); $errors = $this->validator->validate($model); $this->assertFalse($this->hasError('reason', $errors)); // test email $this->assertFalse($this->hasError('email', $errors)); $model->setEmail('test email'); $errors = $this->validator->validate($model); $this->assertTrue($this->hasError('email', $errors)); $model->setEmail('*****@*****.**'); $errors = $this->validator->validate($model); $this->assertFalse($this->hasError('email', $errors)); }
/** * @param $data * @return \Symfony\Component\Validator\ConstraintViolationListInterface */ public function validate($data) { $constraints = [new Assert\NotBlank()]; return $this->validator->validateValue($data, $constraints); }
/** * @dataProvider getObjectsToValidate */ public function testValidateObject($object, $violationCount, $groups = array()) { $this->assertEquals($violationCount, $this->validator->validate($object, $groups)->count()); }
/** * Validate params. * * @param \Symfony\Component\Validator\Validator $validator * @param array $params * @param \Symfony\Component\HttpFoundation\ParameterBag $values * * @return \Symfony\Component\Validator\ConstraintViolationList */ protected function validateParams(Validator $validator, array $params, ParameterBag $values) { $violations = new ConstraintViolationList(); foreach ($params as $param) { if (empty($param['requirements'])) { continue; } $value = $values->get($param['name']); $paramViolations = $validator->validateValue($value, $param['requirements']); // add missing data foreach ($paramViolations as $violation) { $extendedViolation = new ConstraintViolation($violation->getMessage(), $violation->getMessageTemplate(), $violation->getMessageParameters(), $violation->getRoot(), $param['name'] . $violation->getPropertyPath(), $violation->getInvalidValue(), $violation->getMessagePluralization(), $violation->getCode()); $violations->add($extendedViolation); } } return $violations; }
/** * Adds validators to check the Descriptors. * * @param Validator $validator * * @return Validator */ public function attachValidators(Validator $validator) { /** @var ClassMetadata $fileMetadata */ $fileMetadata = $validator->getMetadataFor('phpDocumentor\\Descriptor\\FileDescriptor'); /** @var ClassMetadata $constantMetadata */ $constantMetadata = $validator->getMetadataFor('phpDocumentor\\Descriptor\\ConstantDescriptor'); /** @var ClassMetadata $functionMetadata */ $functionMetadata = $validator->getMetadataFor('phpDocumentor\\Descriptor\\FunctionDescriptor'); /** @var ClassMetadata $classMetadata */ $classMetadata = $validator->getMetadataFor('phpDocumentor\\Descriptor\\ClassDescriptor'); /** @var ClassMetadata $interfaceMetadata */ $interfaceMetadata = $validator->getMetadataFor('phpDocumentor\\Descriptor\\InterfaceDescriptor'); /** @var ClassMetadata $traitMetadata */ $traitMetadata = $validator->getMetadataFor('phpDocumentor\\Descriptor\\TraitDescriptor'); /** @var ClassMetadata $propertyMetadata */ $propertyMetadata = $validator->getMetadataFor('phpDocumentor\\Descriptor\\PropertyDescriptor'); /** @var ClassMetadata $methodMetadata */ $methodMetadata = $validator->getMetadataFor('phpDocumentor\\Descriptor\\MethodDescriptor'); $fileMetadata->addPropertyConstraint('summary', new Assert\NotBlank(array('message' => 'PPC:ERR-50000'))); $classMetadata->addPropertyConstraint('summary', new Assert\NotBlank(array('message' => 'PPC:ERR-50005'))); $propertyMetadata->addConstraint(new phpDocAssert\Property\HasSummary()); $methodMetadata->addPropertyConstraint('summary', new Assert\NotBlank(array('message' => 'PPC:ERR-50008'))); $interfaceMetadata->addPropertyConstraint('summary', new Assert\NotBlank(array('message' => 'PPC:ERR-50009'))); $traitMetadata->addPropertyConstraint('summary', new Assert\NotBlank(array('message' => 'PPC:ERR-50010'))); $functionMetadata->addPropertyConstraint('summary', new Assert\NotBlank(array('message' => 'PPC:ERR-50011'))); $functionMetadata->addConstraint(new phpDocAssert\Functions\IsReturnTypeNotAnIdeDefault()); $methodMetadata->addConstraint(new phpDocAssert\Functions\IsReturnTypeNotAnIdeDefault()); $functionMetadata->addConstraint(new phpDocAssert\Functions\IsParamTypeNotAnIdeDefault()); $methodMetadata->addConstraint(new phpDocAssert\Functions\IsParamTypeNotAnIdeDefault()); $functionMetadata->addConstraint(new phpDocAssert\Functions\AreAllArgumentsValid()); $methodMetadata->addConstraint(new phpDocAssert\Functions\AreAllArgumentsValid()); $classMetadata->addConstraint(new phpDocAssert\Classes\HasSinglePackage()); $interfaceMetadata->addConstraint(new phpDocAssert\Classes\HasSinglePackage()); $traitMetadata->addConstraint(new phpDocAssert\Classes\HasSinglePackage()); $fileMetadata->addConstraint(new phpDocAssert\Classes\HasSinglePackage()); $classMetadata->addConstraint(new phpDocAssert\Classes\HasSingleSubpackage()); $interfaceMetadata->addConstraint(new phpDocAssert\Classes\HasSingleSubpackage()); $traitMetadata->addConstraint(new phpDocAssert\Classes\HasSingleSubpackage()); $fileMetadata->addConstraint(new phpDocAssert\Classes\HasSingleSubpackage()); $classMetadata->addConstraint(new phpDocAssert\Classes\HasPackageWithSubpackage()); $interfaceMetadata->addConstraint(new phpDocAssert\Classes\HasPackageWithSubpackage()); $traitMetadata->addConstraint(new phpDocAssert\Classes\HasPackageWithSubpackage()); $fileMetadata->addConstraint(new phpDocAssert\Classes\HasPackageWithSubpackage()); return $validator; }
/** * Validate given object and compare it to the given errors, with optional validation groups * * @param mixed $object * @param array $errors * @param array $validationGroups */ public function validateObject($object, $errors, array $validationGroups = array()) { $violations = $this->validator->validate($object, $validationGroups); $this->assertEquals($this->countErrors($errors), count($violations), (string) $violations); $this->checkViolationsCoherence($errors, $violations); }