/** * @param mixed $data * @throws MissingDependencyException */ public function validate($data) { if (!$this->validator) { throw new MissingDependencyException('No validator present.'); } return $this->validator->validate($data); }
/** * Validate data * * @param EntityData $data * @throws ValidationException */ public function run(EntityData $data) { $constraintViolations = $this->validator->validate($data); if ($constraintViolations->count()) { throw new ValidationException($constraintViolations); } }
/** * {@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 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"); } } }
/** * @param SourceInterface $source * * @throws ValidationException */ protected function validate(SourceInterface $source) { $violations = $this->validator->validate($source); if ($violations->count()) { throw ValidationException::create($violations); } }
/** * {@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)); } }
/** * 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; }
/** * {@inheritdoc} */ public function validate($entity, array $columnsInfo, array $data, array $errors = array()) { $this->checkIdentifier($entity, $columnsInfo, $data); if (!count($errors)) { return $this->getErrorMap($this->validator->validate($entity)); } else { return $this->validateProperties($entity, $columnsInfo) + $errors; } }
/** * @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; }
/** * @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); } }
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); } }
/** * 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; }
/** * 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); } }
/** * @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 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; }
/** * 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(); }
/** * 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; }
function it_checks_unicity_of_product_value(Product $product1, Product $product2, ColumnInfo $columnInfo1, ColumnInfo $columnInfo2, AttributeInterface $attribute1, AttributeInterface $attribute2, ProductValueInterface $productValue1, ProductValueInterface $productValue2, ProductValueInterface $productValue3, ProductValueInterface $productValue4, ValidatorInterface $validator, ConstraintViolationListInterface $constraint) { $values = [['sku' => 'AKNTS_BPXL', 'test_unique_attribute' => '1200000011a'], ['sku' => '17727158', 'test_unique_attribute' => '1200000011a']]; $columnInfo1->getLabel()->willReturn("sku"); $columnInfo1->getName()->willReturn("sku"); $columnInfo1->getLocale()->willReturn(null); $columnInfo1->getScope()->willReturn(null); $columnInfo1->getAttribute()->willReturn($attribute1); $columnInfo2->getLabel()->willReturn("test_unique_attribute"); $columnInfo2->getName()->willReturn("test_unique_attribute"); $columnInfo2->getLocale()->willReturn(null); $columnInfo2->getScope()->willReturn(null); $columnInfo2->getAttribute()->willReturn($attribute2); $attribute1->isUnique()->willReturn(true); $attribute1->getAttributeType()->willReturn('pim_catalog_text'); $attribute1->getCode()->willReturn('sku'); $attribute2->isUnique()->willReturn(true); $attribute2->getAttributeType()->willReturn('pim_catalog_identifier'); $attribute2->getCode()->willReturn('test_unique_attribute'); $columnsInfo = [$columnInfo1, $columnInfo2]; $product1->getValue("sku", null, null)->shouldBeCalled()->willReturn($productValue1); $product1->getValue("test_unique_attribute", null, null)->shouldBeCalled()->willReturn($productValue2); $product2->getValue("sku", null, null)->shouldBeCalled()->willReturn($productValue3); $product2->getValue("test_unique_attribute", null, null)->shouldBeCalled()->willReturn($productValue4); $productValue1->getAttribute()->willReturn($attribute1); $productValue2->getAttribute()->willReturn($attribute2); $productValue3->getAttribute()->willReturn($attribute1); $productValue4->getAttribute()->willReturn($attribute2); $productValue1->getData()->willReturn("AKNTS_BPXL"); $productValue2->getData()->willReturn("1200000011a"); $productValue3->getData()->willReturn("17727158"); $productValue4->getData()->willReturn("1200000011a"); $productValue1->__toString()->willReturn("AKNTS_BPXL"); $productValue2->__toString()->willReturn("1200000011a"); $productValue3->__toString()->willReturn("17727158"); $productValue4->__toString()->willReturn("1200000011a"); $validator->validateValue('17727158', Argument::any())->shouldBeCalled()->willReturn($constraint); $validator->validateValue('1200000011a', Argument::any())->shouldBeCalled()->willReturn($constraint); $validator->validateValue('AKNTS_BPXL', Argument::any())->shouldBeCalled()->willReturn($constraint); $validator->validate($product1, Argument::any())->shouldBeCalled()->willReturn($constraint); $validator->validate($product2, Argument::any())->shouldBeCalled()->willReturn($constraint); $constraint->count()->willReturn(0); $errors = ['17727158' => [['The value "1200000011a" for unique attribute "test_unique_attribute" was already read in this file']]]; $this->validate($product1, $columnsInfo, $values[0])->shouldReturn([]); $this->validate($product2, $columnsInfo, $values[1])->shouldReturn($errors); }
/** * @param GroupInterface $group * @param array $item */ protected function validateGroup(GroupInterface $group, array $item) { $violations = $this->validator->validate($group); if ($violations->count() !== 0) { $this->detachObject($group); $this->skipItemWithConstraintViolations($item, $violations); } }
/** * @param QueryBuilder $qb */ public function applyRestrictions(QueryBuilder $qb) { if (!$this->groupNode) { return; } $violationList = $this->validator->validate($this->groupNode, new GroupNodeConstraint()); foreach ($violationList as $violation) { throw new LogicException($violation->getMessage()); } list($uncomputedExpr, $computedExpr) = $this->resolveGroupNode($this->groupNode); if ($computedExpr) { $qb->andHaving($computedExpr); } if ($uncomputedExpr) { $qb->andWhere($uncomputedExpr); } }
/** * {@inheritdoc} */ public function setObjectsToMassEdit(array $products) { $this->objects = []; $this->skippedObjects = []; foreach ($products as $product) { if (is_array($product)) { $product = $product[0]; } $violations = $this->validator->validate($product, ['pim_catalog_variant_group']); if ($product instanceof ProductInterface && null === $product->getVariantGroup() && 0 === count($violations)) { $this->objects[] = $product; } else { $this->skippedObjects[] = $product; } } return $this; }
/** * Return if email is valid * * @param string $email Email * * @return boolean Email is valid */ public function validateEmail($email) { if (empty($email)) { return false; } $validationViolationList = $this->validator->validate($email, new Email()); return $validationViolationList->count() === 0; }
/** * @param GroupInterface $variantGroup * @param ArrayCollection $values Collection of ProductValueInterface * @param array $groupData * * @throw InvalidItemException */ protected function validateValues(GroupInterface $variantGroup, ArrayCollection $values, array $groupData) { foreach ($values as $value) { $violations = $this->validator->validate($value); if ($violations->count() !== 0) { $this->detachObject($variantGroup); $this->skipItemWithConstraintViolations($groupData, $violations); } } }
/** * @param ProductInterface[] $products * * @return array ['products' => ProductInterface[], 'violations' => []] */ protected function validateProducts(array $products) { $validProducts = $products; $productViolations = []; // TODO add a service to format violation constraint in the same way foreach ($products as $productIndex => $product) { $violations = $this->productValidator->validate($product); $productIdentifier = (string) $product->getIdentifier(); if ($violations->count() !== 0) { $this->productDetacher->detach($product); unset($validProducts[$productIndex]); $productViolations[$productIdentifier] = []; foreach ($violations as $violation) { $productViolations[$productIdentifier][] = sprintf("%s : %s", $violation->getMessage(), $violation->getInvalidValue()); } } } return ['products' => $validProducts, 'violations' => $productViolations]; }
/** * Validate Marketing List. * * @param MarketingList $marketingList * @return bool */ protected function isValid(MarketingList $marketingList) { $errors = $this->validator->validate($marketingList->getSegment(), array('marketing_list')); if (count($errors) > 0) { /** @var ConstraintViolationInterface $error */ foreach ($errors as $error) { $this->form->addError(new FormError($error->getMessage(), $error->getMessageTemplate(), $error->getMessageParameters(), $error->getMessagePluralization())); } } return $this->form->isValid(); }
/** * @param ProductInterface $product * * @throws \InvalidArgumentException * * @return \Symfony\Component\Validator\ConstraintViolationListInterface|null */ protected function validateProductAssociations(ProductInterface $product) { $associations = $product->getAssociations(); foreach ($associations as $association) { $violations = $this->validator->validate($association); if ($violations->count() > 0) { return $violations; } } return null; }