validateValue() публичный Метод

Validates a given value against a specific Constraint.
public validateValue ( mixed $value, Constraint $constraint, array | null $groups = null ) : ConstraintViolationList
$value mixed The value to validate
$constraint Constraint The constraint to validate against
$groups array | null The validator groups to use for validating
Результат ConstraintViolationList
Пример #1
0
 /**
  * @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;
 }
Пример #2
0
 /**
  * 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;
 }
 protected function validate($value, $constraints = null, $groups = null)
 {
     if (null === $constraints) {
         $constraints = new Valid();
     }
     if ($constraints instanceof Valid) {
         return $this->validator->validate($value, $groups, $constraints->traverse, $constraints->deep);
     }
     return $this->validator->validateValue($value, $constraints, $groups);
 }
Пример #4
0
 /**
  * {@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);
 }
Пример #5
0
 /**
  * @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;
 }
Пример #6
0
 /**
  * Return if email is valid
  *
  * @param string $email Email
  *
  * @return string Email
  */
 public function validateEmail($email)
 {
     if (empty($email)) {
         return false;
     }
     $validationViolationList = $this->validator->validateValue($email, new Email());
     return $validationViolationList->count() == 0;
 }
 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);
 }
Пример #8
0
 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]);
 }
 /**
  * @param mixed                   $value
  * @param string                  $viewValue
  * @param Constraint[]|Constraint $constraints
  * @param string                  $subPath
  * @param ValuesBag               $valuesBag
  * @param string[]                $validationGroups
  */
 private function validateValue($value, $viewValue, $constraints, $subPath, ValuesBag $valuesBag, $validationGroups = null)
 {
     if ($this->validator instanceof LegacyValidator) {
         $violations = $this->validator->validateValue($value, $constraints, $validationGroups);
     } else {
         $violations = $this->validator->validate($value, $constraints, $validationGroups);
     }
     foreach ($violations as $violation) {
         $valuesBag->addError($this->createError($violation, $viewValue, $subPath));
     }
 }
Пример #10
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $entity = $this->buildEntity($form, $form_state);
     $form_state->get('form_display')->validateFormValues($entity, $form, $form_state);
     // Run entity-level validation as well, while skipping validation of all
     // fields. We can do so by fetching and validating the entity-level
     // constraints manually.
     // @todo: Improve this in https://www.drupal.org/node/2395831.
     $typed_entity = $entity->getTypedData();
     $violations = $this->validator->validateValue($entity, $typed_entity->getConstraints());
     foreach ($violations as $violation) {
         $form_state->setErrorByName($violation->getPropertyPath(), $violation->getMessage());
     }
 }
Пример #11
0
 /**
  * Process node online.
  *
  * @param string $locale
  * @param Messages $messages
  * @param NodeInterface $node
  *
  * @return bool
  */
 public function process($locale, Messages $messages, NodeInterface $node)
 {
     if (null === ($nodeTranslation = $node->getTranslation($locale))) {
         $messages->addError($this->translator->trans('node_translation_not_found', array('%locale%' => $locale), 'TadckaSitemapBundle'));
         return false;
     }
     $constraints = array(new NodeRouteNotEmpty(), new NodeParentIsOnline());
     $violation = $this->validator->validateValue($nodeTranslation, $constraints);
     if (0 < $violation->count()) {
         foreach ($violation as $value) {
             $messages->addError($value->getMessage());
         }
         return false;
     }
     if (null !== ($route = $nodeTranslation->getRoute())) {
         if ($route->isVisible()) {
             $this->visibilityManager->setInvisible($locale, $node);
         } else {
             $this->visibilityManager->setVisible($locale, $node);
         }
     }
     return true;
 }
Пример #12
0
 /**
  * {@inheritdoc}
  */
 public function dispatch($generator, $arguments, $path = null, $simulate = false)
 {
     if (is_string($generator)) {
         $generator = $this->registry->getGenerator($generator);
     }
     if (is_array($arguments)) {
         $arguments = new Arguments($arguments);
     }
     $generator->before($arguments);
     $constraints = $generator->getConstraints();
     // retrieve interactive input
     if ($arguments->isForcedInteractive()) {
         $questioner = new Questioner($this->getInputTypeRegistry(), $this->getOutput(), $this->getHelperSet(), $constraints, $this->validator);
         $generator->beforeInteract($arguments);
         $generator->interact($arguments, $questioner);
     }
     // run validation
     $generator->beforeValidate($arguments);
     $constraints = new Collection($constraints);
     $constraints->allowExtraFields = true;
     $problems = $this->validator->validateValue($arguments->getData(), $constraints);
     // stop if any problems are found
     if (count($problems) > 0) {
         $this->showValidationProblems($problems, $generator);
         throw new ValidationException("Generator failed because of validation errors");
     }
     // create a builder for this specific generator
     $generator->beforeGenerate($arguments);
     $builder = $this->builder->forGenerator($generator, $arguments);
     if ($path !== null) {
         $builder = $builder->withPath($path);
     }
     $builder->simulated($simulate);
     // run the generator
     $generator->setOutput($this->output);
     $generator->generate($arguments, $builder, $this);
 }
Пример #13
0
 /**
  * Controller.
  *
  * @param FilterControllerEvent $event The event
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     $request = $this->request = $event->getRequest();
     if ($request->attributes->has('start') && $request->attributes->has('count')) {
         return;
     }
     if (false === $this->isEnabled()) {
         return;
     }
     $controller = $event->getController();
     if (false === in_array($request->getMethod(), array('GET', 'HEAD', 'DELETE'))) {
         // pagination only makes sense with GET or DELETE methods
         return;
     }
     $metadata = $this->getControllerActionMetadata($controller);
     if (null === $metadata || null === $metadata->default_start) {
         // no annotations defined for this controller
         return;
     }
     $start = $metadata->default_start;
     $count = $metadata->default_count;
     $range = explode(',', $request->headers->get('Range'));
     if (true === isset($range[0])) {
         $start = intval($range[0]);
     }
     if (true === isset($range[1])) {
         $count = intval($range[1]);
     }
     $violations = new ConstraintViolationList();
     $start_violations = $this->validator->validateValue($start, array(new \Symfony\Component\Validator\Constraints\Type(array('type' => 'numeric', 'message' => 'Headers "Range" attribute first operand (=start) must be a positive integer')), new \Symfony\Component\Validator\Constraints\Range(array('min' => 0, 'minMessage' => 'Headers "Range" attribute first operand (=start) must be a positive integer'))));
     $count_label = 'Headers "Range" attribute second operand (=count)';
     $count_violations = $this->validator->validateValue($count, array(new \Symfony\Component\Validator\Constraints\Type(array('type' => 'numeric', 'message' => "{$count_label} must be a positive integer")), new \Symfony\Component\Validator\Constraints\Range(array('min' => $metadata->min_count, 'minMessage' => "{$count_label} must be greater than or equal to " . $metadata->min_count, 'max' => $metadata->max_count, 'maxMessage' => "{$count_label} must be less than or equal to " . $metadata->max_count))));
     $violations->addAll($start_violations);
     $violations->addAll($count_violations);
     $violation_param = $this->getViolationsParameterName($metadata);
     if (null !== $violation_param) {
         // if action has an argument for violations, pass it
         $request->attributes->set($violation_param, $violations);
     } elseif (0 < count($violations)) {
         // if action has no arg for violations and there is at least one, throw an exception
         throw new ValidationException($violations);
     }
     // add pagination properties to attributes
     $request->attributes->set('start', $start);
     $request->attributes->set('count', $count);
     // remove pagination properties from headers
     $request->headers->remove('Range');
 }
 /**
  * Adds a requirement to the completenesses
  *
  * @param array                         &$completenesses
  * @param AttributeRequirementInterface $requirement
  * @param ArrayCollection               $productValues
  * @param array                         $localeCodes
  */
 protected function addRequirementToCompleteness(array &$completenesses, AttributeRequirementInterface $requirement, ArrayCollection $productValues, array $localeCodes)
 {
     $attribute = $requirement->getAttribute();
     $channel = $requirement->getChannel();
     foreach ($localeCodes as $localeCode) {
         $constraint = new ProductValueComplete(array('channel' => $channel));
         $valueCode = $this->getValueCode($attribute, $localeCode, $channel->getCode());
         $missing = false;
         if (!isset($productValues[$valueCode])) {
             $missing = true;
         } elseif ($this->validator->validateValue($productValues[$valueCode], $constraint)->count()) {
             $missing = true;
         }
         if ($missing) {
             $completenesses[$localeCode][$channel->getCode()]['missing'][] = $attribute;
         }
     }
 }
Пример #15
0
 /**
  * @param array $item
  *
  * @return boolean
  */
 public function __invoke(array $item)
 {
     if (!$this->strict) {
         // Only validate properties which have an constaint.
         $temp = array_intersect(array_keys($item), array_keys($this->constraints));
         $item = array_intersect_key($item, array_flip($temp));
     }
     $constraints = new Constraints\Collection($this->constraints);
     $list = $this->validator->validateValue($item, $constraints);
     $currentLine = $this->line++;
     if (count($list) > 0) {
         $this->violations[$currentLine] = $list;
         if ($this->throwExceptions) {
             throw new ValidationException($list, $currentLine);
         }
     }
     return 0 === count($list);
 }
Пример #16
0
 /**
  * @param \WeavingTheWeb\Bundle\DashboardBundle\Entity\Perspective $perspective
  * @return \Symfony\Component\Validator\ConstraintViolationListInterface
  */
 protected function validatePerspectiveValue($perspective)
 {
     $queryConstraint = new Query();
     return $this->validator->validateValue($perspective->getValue(), $queryConstraint, $queryConstraint::GROUP_PUBLIC_QUERIES);
 }
Пример #17
0
 /**
  * @return \Symfony\Component\Validator\ConstraintViolationListInterface
  */
 protected function validate(array $item)
 {
     $constraints = new Constraints\Collection($this->collectionConstraintOptions);
     $list = $this->validator->validateValue($item, $constraints);
     return $list;
 }
Пример #18
0
 /**
  * Iterate over all the set rules on this field and validate them
  * Upon failed validation we set the error message and return false
  *
  * @todo garyttierney - do we want the Form to handle validation for every input or should that be left to an element?
  *       if the latter, we should share a single Validator object between all of them.
  *
  * @param $input string|array
  * @return ElementValidationResult
  */
 public function validate($input, ValidatorInterface $validator)
 {
     // @todo - note, this will be removed in Symfony 3.0 and there's currently no way around that
     $validatorResult = $validator->validateValue($input, $this->getConstraints());
     if (count($validatorResult) === 0) {
         return new ElementValidationResult(true);
     } else {
         $errorMessages = array();
         foreach ($validatorResult as $constraintViolation) {
             $errorMessages[] = $constraintViolation->getMessage();
         }
         return new ElementValidationResult(false, $errorMessages);
     }
 }