/** * @param Container $container * @param object $entity * @return \Symfony\Component\Validator\ConstraintViolationInterface[]|ConstraintViolationList */ public function validateContainer(Container $container, $entity) { if ($entity === NULL) { return; } $meta = $this->em->getClassMetadata(get_class($entity)); $groups = NULL; if ($entity instanceof GroupSequenceProviderInterface) { $groups = $entity->getGroupSequence(); } /** @var ConstraintViolationList|ConstraintViolationInterface[] $violations */ $violations = $this->validator->validate($entity, $groups); $this->mapViolationsToForm($container, $violations); foreach ($container->getComponents(FALSE, 'Nette\\Forms\\Container') as $child) { /** @var Nette\Forms\Container $child */ if (!$meta->hasAssociation($field = $child->getName())) { continue; } if ($meta->isSingleValuedAssociation($field)) { $this->validateContainer($child, $meta->getFieldValue($entity, $field)); } else { throw new NotImplementedException("To many relation is not yet implemented"); } } }
/** * Validate data * * @param EntityData $data * @throws ValidationException */ public function run(EntityData $data) { $constraintViolations = $this->validator->validate($data); if ($constraintViolations->count()) { throw new ValidationException($constraintViolations); } }
public function setUp() { parent::setUp(); $this->validator = $this->getMock('Symfony\\Component\\Validator\\ValidatorInterface'); $this->validator->expects($this->never())->method('validate')->will($this->returnValue(array())); $this->listener = new ValidationListener($this->validator); }
/** * @param SourceInterface $source * * @throws ValidationException */ protected function validate(SourceInterface $source) { $violations = $this->validator->validate($source); if ($violations->count()) { throw ValidationException::create($violations); } }
/** * {@inheritdoc} * * Expected input format : * { * 'attribute': 'maximum_print_size', * 'code': '210_x_1219_mm', * 'sort_order': 2, * 'labels': { * 'de_DE': '210 x 1219 mm', * 'en_US': '210 x 1219 mm', * 'fr_FR': '210 x 1219 mm' * } * } * * @throws BusinessValidationException */ public function update($attributeOption, array $data, array $options = []) { if (!$attributeOption instanceof AttributeOptionInterface) { throw new \InvalidArgumentException(sprintf('Expects a "Pim\\Bundle\\CatalogBundle\\Model\\AttributeOptionInterface", "%s" provided.', ClassUtils::getClass($attributeOption))); } // TODO: ugly fix to workaround issue with "attribute.group.code: This value should not be blank." // in case of existing option, attribute is a proxy, attribute group too, the validated group code is null $attributeOption->getAttribute() !== null ? $attributeOption->getAttribute()->getGroup()->getCode() : null; $isNew = $attributeOption->getId() === null; $readOnlyFields = ['attribute', 'code']; $updateViolations = new ConstraintViolationList(); foreach ($data as $field => $data) { $isReadOnlyField = in_array($field, $readOnlyFields); if ($isNew || !$isReadOnlyField) { try { $this->setData($attributeOption, $field, $data); } catch (\InvalidArgumentException $e) { $setViolation = new ConstraintViolation($e->getMessage(), $e->getMessage(), [], $attributeOption, null, null); $updateViolations->add($setViolation); } } } $validatorViolations = $this->validator->validate($attributeOption); $updateViolations->addAll($validatorViolations); if ($updateViolations->count() > 0) { throw new BusinessValidationException($updateViolations); } return $this; }
/** * @param string|InputTypeInterface $type * @param array $options * @param Constraint[]|Constraint $constraints * @return mixed * @throws InputTypeNotFoundException */ public function ask($type, array $options = []) { if (is_string($type)) { $type = $this->types->getType($type); } if (!$type instanceof InputTypeInterface) { throw new InputTypeNotFoundException("Type should be an instance of InputTypeInterface or a string"); } $options = $this->validateAndUpdateOptions($options, $type); $value = $options['default']; while (true) { $value = $type->ask($options, $this); if (is_callable($options['modify'])) { $value = call_user_func($options['modify'], $value); } if ($options['constraints'] !== null) { $problems = $this->validator->validateValue($value, $options['constraints']); if (count($problems) > 0) { $messages = ["There were some errors in the provided value:", ""]; /** @var ConstraintViolation $problem */ foreach ($problems as $problem) { $messages[] = "{$problem->getMessage()}"; } /** @var FormatterHelper $formatter */ $formatter = $this->getHelper('formatter'); $this->getOutput()->writeln($formatter->formatBlock($messages, 'error', true)); continue; } } break; } return $value; }
/** * @param mixed $data * @throws MissingDependencyException */ public function validate($data) { if (!$this->validator) { throw new MissingDependencyException('No validator present.'); } return $this->validator->validate($data); }
private function validateXApiValidator(ValidatorInterface $validator) { $metadataFactory = $validator->getMetadataFactory(); $this->assertTrue($metadataFactory->hasMetadataFor('\\XApi\\Model\\Activity')); $this->assertTrue($metadataFactory->hasMetadataFor('\\XApi\\Model\\Agent')); $this->assertTrue($metadataFactory->hasMetadataFor('\\XApi\\Model\\Activity')); $this->assertTrue($metadataFactory->hasMetadataFor('\\XApi\\Model\\Activity')); }
/** * {@inheritdoc} */ public function process(VariableInterface $variable, VariantInterface $variant) { if (0 < count($this->validator->validate($variant, array('sylius')))) { $variable->removeVariant($variant); } else { $this->eventDispatcher->dispatch('sylius.variant.pre_create', new GenericEvent($variant)); } }
/** * Validate upload image. * * @param UploadedFile $uploadedImage * @param array $config * * @return array */ private function validateUploadImage(UploadedFile $uploadedImage, array $config) { $errors = array(); foreach ($this->validator->validateValue($uploadedImage, $this->getConstraint($config)) as $error) { $errors[] = $error->getMessage(); } return $errors; }
/** * Add a new enrichment to the indexer * * @param \Searchperience\Api\Client\Domain\Enrichment\Enrichment $enrichment * @throws \Searchperience\Common\Exception\InvalidArgumentException * @return integer HTTP Status code */ public function add(\Searchperience\Api\Client\Domain\Enrichment\Enrichment $enrichment) { $violations = $this->enrichmentValidator->validate($enrichment); if ($violations->count() > 0) { throw new \Searchperience\Common\Exception\InvalidArgumentException('Given object of type "' . get_class($enrichment) . '" is not valid: ' . PHP_EOL . $violations); } $status = $this->storageBackend->post($enrichment); return $status; }
/** * @param object $filter * @throws \Searchperience\Common\Exception\InvalidArgumentException */ protected function validateFilter($filter) { $this->loadConstraints(); $this->injectValidator(\Symfony\Component\Validator\Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator()); $violations = $this->filterValidator->validate($filter); if ($violations->count() > 0) { throw new \Searchperience\Common\Exception\InvalidArgumentException('Given object of type "' . get_class($violations) . '" is not valid: ' . $violations); } }
/** * @{inheritdoc} */ public function validate($object, Violation\ViolationList $violationList) { $errors = $this->validator->validate($object); foreach ($errors as $error) { $constraint = call_user_func_array(array($this->model, 'createFromConstraintViolation'), array($error)); $violationList->add($constraint); } return $violationList; }
/** * Add a new Document to the index * * @param \Searchperience\Api\Client\Domain\UrlQueueItem\UrlQueueItem $urlQueueItem * @throws \Searchperience\Common\Exception\InvalidArgumentException * @return integer HTTP Status code */ public function add(\Searchperience\Api\Client\Domain\UrlQueueItem\UrlQueueItem $urlQueueItem) { $violations = $this->urlQueueValidator->validate($urlQueueItem); if ($violations->count() > 0) { throw new InvalidArgumentException('Given object of type "' . get_class($urlQueueItem) . '" is not valid: ' . PHP_EOL . $violations); } $status = $this->storageBackend->post($urlQueueItem); return $status; }
function it_validates_an_item_and_the_validation_fails_with_exception(ValidatorInterface $validator, Constraint $constraint, ConstraintViolationList $list) { $list->count()->willReturn(1); $validator->validateValue($this->item1, Argument::type('Symfony\\Component\\Validator\\Constraints\\Collection'))->willReturn($list); $this->throwExceptions(true); $this->add('key1', $constraint); $this->shouldThrow('Ddeboer\\DataImport\\Exception\\ValidationException')->during__invoke($this->item1); $this->getViolations()->shouldReturn([1 => $list]); }
public function saveCart(CartEvent $event) { $cart = $event->getCart(); $errors = $this->validator->validate($cart); $valid = 0 === count($errors); if ($valid) { $this->cartManager->persist($cart); $this->cartManager->flush(); $this->cartProvider->setCart($cart); } }
/** * @param object $object */ public function validate($object) { $flattenedErros = array(); $errors = $this->validator->validate($object); if (count($errors) > 0) { foreach ($errors as $error) { $flattenedErros[$error->getPropertyPath()] = $error->getMessage(); } throw new InvalidException("Object is invalid", $flattenedErros); } }
private function validateXApiValidator(ValidatorInterface $validator) { if ($validator instanceof MetadataFactoryInterface) { $metadataFactory = $validator; } else { $metadataFactory = $validator->getMetadataFactory(); } $this->assertTrue($metadataFactory->hasMetadataFor('\\Xabbuh\\XApi\\Model\\Activity')); $this->assertTrue($metadataFactory->hasMetadataFor('\\Xabbuh\\XApi\\Model\\Agent')); $this->assertTrue($metadataFactory->hasMetadataFor('\\Xabbuh\\XApi\\Model\\Activity')); $this->assertTrue($metadataFactory->hasMetadataFor('\\Xabbuh\\XApi\\Model\\Activity')); }
/** * {@inheritdoc} */ public function buildView(FormView $view, FormInterface $form, array $options) { $fieldName = $view->vars['full_name']; $parentForm = $form->getParent(); if (!empty($parentForm)) { $config = $parentForm->getConfig(); $options = $config->getOptions(); $validationGroups = $options['validation_groups']; $dataClass = $config->getDataClass(); $entityMetadata = $dataClass !== null ? $this->validator->getMetadataFor($dataClass) : null; $view->vars['entity_constraints'] = $this->prepareConstraintsAttributes($fieldName, $entityMetadata, $validationGroups); } }
/** * Validate entity, returns list of errors or null * * @param object $entity * @return array|null */ public function validateEntity($entity) { $violations = $this->validator->validate($entity); if (count($violations)) { $errors = array(); /** @var ConstraintViolationInterface $violation */ foreach ($violations as $violation) { $errors[] = sprintf(sprintf('%s: %s', $violation->getPropertyPath(), $violation->getMessage())); } return $errors; } return null; }
/** * {@inheritdoc} */ public function process(&$item) { $constraints = new Constraints\Collection($this->constraints); $list = $this->validator->validateValue($item, $constraints); if (count($list) > 0) { $this->violations[$this->line] = $list; if ($this->throwExceptions) { throw new ValidationException($list, $this->line); } } $this->line++; return 0 === count($list); }
/** * Validates one entity. * * @param BaseEntity $entity * @throws \App\Exceptions\EntityValidationException */ private function validateEntity(BaseEntity $entity) { /** @var ConstraintViolationListInterface $violationList */ $violationList = $this->validator->validate($entity); if ($violationList->count() > 0) { $msg = ""; /** @var ConstraintViolationInterface $violation */ foreach ($violationList as $violation) { $msg .= get_class($violation->getRoot()) . '::$' . $violation->getPropertyPath(); $msg .= ' ' . $violation->getMessage() . PHP_EOL; } throw new EntityValidationException($msg); } }
/** * Test preparing array of constraints based on entity metadata */ public function testPrepareConstraintsAttributes() { $entityMetadata = $this->validator->getMetadataFor('Sleepness\\UberFrontendValidationBundle\\Tests\\Fixtures\\Model\\Post'); $reflectedMethod = new ReflectionMethod($this->extension, 'prepareConstraintsAttributes'); $reflectedMethod->setAccessible(TRUE); $preparedConstraintsAttributes = $reflectedMethod->invoke($this->extension, 'post[title]', $entityMetadata, array('Default')); $fullFieldNames = array_keys($preparedConstraintsAttributes); $constraintNames = array_keys($preparedConstraintsAttributes[$fullFieldNames[0]]); $constraintProperties = array_keys($preparedConstraintsAttributes[$fullFieldNames[0]][$constraintNames[0]]); $this->assertEquals('post[title]', $fullFieldNames[0]); $this->assertEquals('NotBlank', $constraintNames[0]); $this->assertEquals('Length', $constraintNames[1]); $this->assertEquals('message', $constraintProperties[0]); $this->assertEquals('Title should not be blank!', $preparedConstraintsAttributes[$fullFieldNames[0]][$constraintNames[0]]['message']); }
/** * Stores the object in the request. * * @param Request $request The request * @param ParamConverter $configuration Contains the name, class and options of the object * * @return boolean True if the object has been successfully set, else false * * @throws UnsupportedMediaTypeHttpException * @throws BadRequestHttpException */ protected function execute(Request $request, ParamConverter $configuration) { $options = (array) $configuration->getOptions(); if (isset($options['deserializationContext']) && is_array($options['deserializationContext'])) { $context = array_merge($this->context, $options['deserializationContext']); } else { $context = $this->context; } if ($this->serializer instanceof SerializerInterface) { $context = $this->configureDeserializationContext($this->getDeserializationContext(), $context); } try { $object = $this->serializer->deserialize($request->getContent(), $configuration->getClass(), $request->getContentType(), $context); } catch (UnsupportedFormatException $e) { throw new UnsupportedMediaTypeHttpException($e->getMessage()); } catch (JMSSerializerException $e) { throw new BadRequestHttpException($e->getMessage()); } catch (SymfonySerializerException $e) { throw new BadRequestHttpException($e->getMessage()); } $request->attributes->set($configuration->getName(), $object); if (null !== $this->validator) { $validatorOptions = $this->getValidatorOptions($options); $request->attributes->set($this->validationErrorsArgument, $this->validator->validate($object, $validatorOptions['groups'], $validatorOptions['traverse'], $validatorOptions['deep'])); } return true; }
/** * Validate the product * * @param ProductInterface $product * * @return bool */ protected function isProductValid(ProductInterface $product) { $violations = $this->validator->validate($product); $this->addWarningMessage($violations, $product); return 0 === $violations->count(); }
/** * @param Request $request * @param string $id * * @throws NotFoundHttpException If product is not found or the user cannot see it * @throws AccessDeniedHttpException If the user does not have right to edit the product * * @return JsonResponse */ public function postAction(Request $request, $id) { $product = $this->findProductOr404($id); if ($this->objectFilter->filterObject($product, 'pim.internal_api.product.edit')) { throw new AccessDeniedHttpException(); } $data = json_decode($request->getContent(), true); try { $data = $this->productEditDataFilter->filterCollection($data, null); } catch (ObjectNotFoundException $e) { throw new BadRequestHttpException(); } // TODO: PEF should never update groups, no way to do so from the screen, if a product is added to // another group during the save, this relation will be removed, other issue is that variant groups are never // passed here, so a product is always removed from it's variant group when saved unset($data['groups']); $this->updateProduct($product, $data); $violations = $this->validator->validate($product); if (0 === $violations->count()) { $this->productSaver->save($product); return new JsonResponse($this->normalizer->normalize($product, 'internal_api')); } else { $errors = $this->transformViolations($violations, $product); return new JsonResponse($errors, 400); } }
/** * @param AttributeOptionInterface $attributeOption * * @throws \InvalidArgumentException * * @return ConstraintViolationListInterface */ protected function validateAttributeOption(AttributeOptionInterface $attributeOption) { // TODO: ugly fix to workaround issue with "attribute.group.code: This value should not be blank." // in case of existing option, attribute is a proxy, attribute group too, the validated group code is null null !== $attributeOption->getAttribute() ? $attributeOption->getAttribute()->getGroup()->getCode() : null; return $this->validator->validate($attributeOption); }
/** * @param Param $config config * @param string $param param to clean * @param boolean $strict is strict * * @throws BadRequestHttpException * @return string */ public function cleanParamWithRequirements(Param $config, $param, $strict) { $default = $config->default; if (null === $config->requirements || $param === $default && null !== $default) { return $param; } $constraint = $config->requirements; if (is_scalar($constraint)) { if (is_array($param)) { if ($strict) { throw new BadRequestHttpException("Query parameter is an array"); } return $default; } $constraint = new Regex(array('pattern' => '#^' . $config->requirements . '$#xsu', 'message' => sprintf("%s parameter value '%s', does not match requirements '%s'", $config instanceof QueryParam ? 'Query' : 'Request', $param, $config->requirements))); } $errors = $this->validator->validateValue($param, $constraint); if (0 !== count($errors)) { if ($strict) { throw new BadRequestHttpException((string) $errors); } return null === $default ? '' : $default; } return $param; }
/** * @param string $operationAlias * * @AclAncestor("pim_enrich_mass_edit") * @throws NotFoundHttpException * @return Response|RedirectResponse */ public function performAction($operationAlias) { try { $operator = $this->operatorRegistry->getOperator($this->request->get('gridName')); $operator->setOperationAlias($operationAlias)->setObjectsToMassEdit($this->getObjects()); } catch (\InvalidArgumentException $e) { throw $this->createNotFoundException($e->getMessage(), $e); } if ($this->isExecutable() === false) { return $this->redirectToRoute($operator->getPerformedOperationRedirectionRoute()); } $operator->initializeOperation(); $form = $this->getOperatorForm($operator, ['Default', 'configureAction']); $form->submit($this->request); if ($form->isValid()) { $operator->performOperation(); // Binding does not actually perform the operation, thus form errors can miss some constraints foreach ($this->validator->validate($operator) as $violation) { $form->addError(new FormError($violation->getMessage(), $violation->getMessageTemplate(), $violation->getMessageParameters(), $violation->getMessagePluralization())); } } if ($form->isValid()) { $operator->finalizeOperation(); $this->addFlash('success', sprintf('pim_enrich.mass_edit_action.%s.success_flash', $operationAlias)); return $this->redirectToRoute($operator->getPerformedOperationRedirectionRoute()); } return $this->render(sprintf('PimEnrichBundle:MassEditAction:configure/%s.html.twig', $operationAlias), array('form' => $form->createView(), 'operator' => $operator, 'productCount' => $this->getObjectCount(), 'queryParams' => $this->getQueryParams())); }
/** * {@inheritDoc} */ public function apply(Request $request, ConfigurationInterface $configuration) { $options = (array) $configuration->getOptions(); if (isset($options['deserializationContext']) && is_array($options['deserializationContext'])) { $context = array_merge($this->context, $options['deserializationContext']); } else { $context = $this->context; } if ($this->serializer instanceof SerializerInterface) { $context = $this->configureDeserializationContext($this->getDeserializationContext(), $context); } try { $object = $this->serializer->deserialize($request->getContent(), $configuration->getClass(), $request->getContentType(), $context); } catch (UnsupportedFormatException $e) { throw new HttpException(Codes::HTTP_UNSUPPORTED_MEDIA_TYPE, $e->getMessage()); } catch (JMSSerializerException $e) { throw new HttpException(Codes::HTTP_BAD_REQUEST, $e->getMessage()); } catch (SymfonySerializerException $e) { throw new HttpException(Codes::HTTP_BAD_REQUEST, $e->getMessage()); } $request->attributes->set($configuration->getName(), $object); if (null !== $this->validator) { $validatorOptions = $this->getValidatorOptions($options); $request->attributes->set($this->validationErrorsArgument, $this->validator->validate($object, $validatorOptions['groups'], $validatorOptions['traverse'], $validatorOptions['deep'])); } return true; }