Валидация параметров запроса

@throws \Symfony\Component\Validator\Exception\MissingOptionsException
@throws \Symfony\Component\Validator\Exception\InvalidOptionsException
@throws \Symfony\Component\Validator\Exception\ConstraintDefinitionException
6728
public function validateData()
    {
        $constraint = new Assert\Collection([
            'fields' => $this->getValidationRules(),
        ]);

        $violations = $this->validator->validate($this->getParameters(), $constraint);
        if ($violations->count()) {
            throw new ValidatorException($violations);
        }

        return $this;
    }
1188440
private function initOptions()
    {
        $this->optionsResolver->setDefaults([
            'entity' => null,
            'qb' => null,
            'alias' => null,
            'em' => null,
            'useOutputWalkers' => null,
        ]);

        $this->optionsResolver->setAllowedTypes('entity', ['string', 'null']);
        $this->optionsResolver->setAllowedTypes('qb', ['\Doctrine\ORM\QueryBuilder', 'null']);
        $this->optionsResolver->setAllowedTypes('alias', ['null', 'string']);
        $this->optionsResolver->setAllowedTypes('em', ['null', 'string']);
        $this->optionsResolver->setAllowedTypes('useOutputWalkers', ['null', 'bool']);

        $entityNormalizer = function(Options $options, $value) {
            if (is_null($options['qb']) && is_null($value)) {
                throw new InvalidOptionsException('You must specify at least one option, "qb" or "entity".');
            }

            return $value;
        };

        $this->optionsResolver->setNormalizer('entity', $entityNormalizer);
    }
210613
private function getOptionsResolver()
    {
        if (null === self::$optionsResolver) {
            $classExists = function ($class) {
                if (!class_exists($class)) {
                    throw new InvalidOptionsException(sprintf('Class %s does not exists.', $class));
                }
                return true;
            };
            $classExistsAndImplements = function($class, $interface) use ($classExists) {
                $classExists($class);
                if (!in_array($interface, class_implements($class))) {
                    throw new InvalidOptionsException(sprintf('Class %s must implement %s.', $class, $interface));
                }
                return true;
            };
            $validOperator = function ($class) use ($classExistsAndImplements) {
                return $classExistsAndImplements($class, self::OPERATOR_INTERFACE);
            };
            $validController = function ($class) use ($classExistsAndImplements) {
                return $classExistsAndImplements($class, self::CONTROLLER_INTERFACE);
            };
            $validForm = function ($class) use ($classExistsAndImplements) {
                return $classExistsAndImplements($class, self::FORM_INTERFACE);
            };
            $validTable = function ($class) use ($classExistsAndImplements) {
                return $classExistsAndImplements($class, self::TABLE_INTERFACE);
            };
            $validEvent = function ($class) use ($classExistsAndImplements) {
                if (null === $class) {
                    return true;
                }
                return $classExistsAndImplements($class, self::EVENT_INTERFACE);
            };

            self::$optionsResolver = new OptionsResolver();
            /** @noinspection PhpUnusedParameterInspection */
            self::$optionsResolver
                ->setDefaults([
                    'entity'      => null,
                    'repository'  => null,
                    'operator'    => self::DEFAULT_OPERATOR,
                    'controller'  => self::DEFAULT_CONTROLLER,
                    'templates'   => null,
                    'form'        => null,
                    'table'       => null,
                    'event'       => null,
                    'parent'      => null,
                    'translation' => null,
                ])

                ->setAllowedTypes('entity',      'string')
                ->setAllowedTypes('repository',  ['null', 'string'])
                ->setAllowedTypes('operator',    'string')
                ->setAllowedTypes('controller',  'string')
                ->setAllowedTypes('templates',   ['null', 'string', 'array'])
                ->setAllowedTypes('form',        'string')
                ->setAllowedTypes('table',       'string')
                ->setAllowedTypes('event',       ['null', 'string'])
                ->setAllowedTypes('parent',      ['null', 'string'])
                ->setAllowedTypes('translation', ['null', 'array'])

                ->setAllowedValues('entity',     $classExists)
                ->setAllowedValues('operator',   $validOperator)
                ->setAllowedValues('controller', $validController)
                ->setAllowedValues('form',       $validForm)
                ->setAllowedValues('table',      $validTable)
                ->setAllowedValues('event',      $validEvent)

                ->setNormalizer('repository', function($options, $value) use ($classExistsAndImplements) {
                    $translatable = is_array($options['translation']);
                    $interface = $translatable ? self::TRANSLATABLE_REPOSITORY_INTERFACE : self::REPOSITORY_INTERFACE;
                    if (null === $value) {
                        if ($translatable) {
                            $value = self::TRANSLATABLE_DEFAULT_REPOSITORY;
                        } else {
                            $value = self::DEFAULT_REPOSITORY;
                        }
                    }
                    $classExistsAndImplements($value, $interface);
                    return $value;
                })
                ->setNormalizer('translation', function ($options, $value) use ($classExistsAndImplements) {
                    if (is_array($value)) {
                        if (!array_key_exists('entity', $value)) {
                            throw new InvalidOptionsException('translation.entity must be defined.');
                        }
                        if (!array_key_exists('fields', $value)) {
                            throw new InvalidOptionsException('translation.fields must be defined.');
                        }
                        if (!is_array($value['fields']) || empty($value['fields'])) {
                            throw new InvalidOptionsException('translation.fields can\'t be empty.');
                        }
                        if (!array_key_exists('repository', $value)) {
                            $value['repository'] = self::DEFAULT_REPOSITORY;
                        }
                        $classExistsAndImplements($value['repository'], self::REPOSITORY_INTERFACE);
                    }
                    return $value;
                })
                // TODO templates normalization ?
            ;
        }
        return self::$optionsResolver;
    }
504402
public function validate($array, Constraint $constraint): void
    {
        if ($array !== null) {
            if (!\is_array($array)) {
                $this->context->buildViolation('Должно быть массивом')
                    ->addViolation();
            } else {
                /**
                 * @var Enum $type
                 */
                $type = $constraint->type;

                $badValues = [];
                foreach ($array as $i => $v) {
                    if (\call_user_func($type . '::check', [$v]) === false) {
                        $badValues[] = $i . ' => ' . $v;
                    }
                }
                if (\count($badValues) > 0) {
                    $this->context->buildViolation($constraint->message)
                        ->setParameter('{{ type }}', $constraint->type)
                        ->setParameter('{{ value }}', implode(', ', $badValues))
                        ->addViolation();
                }
            }
        }
    }
189306
public function validate() {
		parent::validate();

		if ($this->getName() === null) {
			throw new ValidationException("'name' can't be null", 'name', $this);
		}
		if ($this->getType() === null) {
			throw new ValidationException("'type' can't be null", 'type', $this);
		}
	}
183327
private function validate()
    {
        if (null === $this->provider) {
            throw new MissingProviderException('A provider must be set for converting a currency');
        }

        if (null === $this->from || null === $this->to) {
            throw new \RuntimeException('from and to parameters must be provided');
        }
    }
947250
private function getOptionsResolver()
    {
        // TODO Use/Merge ConfigurationBuilder options resolver.
        if (!$this->optionsResolver) {
            $resolver = new OptionsResolver();

            $resolver
                ->setRequired(['namespace', 'id', 'classes'])
                ->setDefaults([
                    'name'        => function (Options $options) {
                        return Inflector::camelize($options['id']);
                    },
                    'parent_id'   => null,
                    'event'       => null,
                    'templates'   => null,
                    'translation' => null,
                ])
                ->setAllowedTypes('namespace', 'string')
                ->setAllowedTypes('id', 'string')
                ->setAllowedTypes('name', 'string')
                ->setAllowedTypes('parent_id', ['null', 'string'])
                ->setAllowedTypes('classes', 'array')
                ->setAllowedTypes('event', ['null', 'string', 'array'])
                ->setAllowedTypes('templates', ['null', 'string', 'array'])
                ->setAllowedTypes('translation', ['null', 'array']);


            // Classes option
            $classesResolver = new OptionsResolver();
            $classesResolver
                ->setRequired(['entity'])
                ->setDefaults([
                    'form_type'  => null, // @TODO/WARNING no longer required (behavior refactoring)
                    'repository' => null,
                ])
                ->setAllowedTypes('entity', 'string')
                ->setAllowedTypes('repository', ['null', 'string'])
                ->setAllowedTypes('form_type', ['null', 'string']); // @TODO/WARNING no longer required (behavior refactoring)

            $resolver
                ->setNormalizer('classes', function (Options $options, $value) use ($classesResolver) {
                    foreach ($value as $class) {
                        if ($class && !class_exists($class)) {
                            throw new InvalidOptionsException(sprintf("Class '%s' does not exists.", $class));
                        }
                    }

                    $entity = $value['entity'];
                    if (null !== $options['translation'] && !is_subclass_of($entity, TranslatableInterface::class)) {
                        throw new InvalidOptionsException(sprintf(
                            "Class '%s' must implements '%s'.",
                            $entity,
                            TranslatableInterface::class));
                    }

                    $repository = array_key_exists('repository', $value) ? $value['repository'] : null;
                    if (null === $repository) {
                        $value['repository'] = null !== $options['translation']
                            ? TranslatableResourceRepository::class
                            : ResourceRepository::class;
                    } elseif (null !== $options['translation']) {
                        if (!is_subclass_of($repository, TranslatableResourceRepositoryInterface::class)) {
                            throw new InvalidOptionsException(sprintf(
                                "Class '%s' must implements '%s'.",
                                $repository,
                                TranslatableResourceRepositoryInterface::class
                            ));
                        }
                    } else {
                        if (!is_subclass_of($repository, ResourceRepositoryInterface::class)) {
                            throw new InvalidOptionsException(sprintf(
                                "Class '%s' must implements '%s'.",
                                $repository,
                                ResourceRepositoryInterface::class
                            ));
                        }
                    }

                    return $classesResolver->resolve($value);
                });


            // Translation option
            $translationResolver = new OptionsResolver();
            $translationResolver
                ->setRequired(['entity', 'fields'])
                ->setDefault('repository', null)
                ->setAllowedTypes('entity', 'string')
                ->setAllowedTypes('fields', 'array')
                ->setAllowedTypes('repository', ['null', 'string'])
                ->setAllowedValues('entity', function ($class) {
                    if (!class_exists($class)) {
                        throw new InvalidOptionsException(sprintf("Class '%s' does not exists.", $class));
                    }
                    if (!is_subclass_of($class, TranslationInterface::class)) {
                        throw new InvalidOptionsException(sprintf("Class '%s' must implements '%s'.", $class, TranslationInterface::class));
                    }

                    return true;
                })
                ->setAllowedValues('fields', function ($fields) {
                    if (empty($fields)) {
                        throw new InvalidOptionsException("Translatable fields cannot be empty.");
                    }

                    return true;
                })
                ->setAllowedValues('repository', function ($class) {
                    if (null !== $class && !class_exists($class)) {
                        throw new InvalidOptionsException(sprintf("Class '%s' does not exists.", $class));
                    }

                    return true;
                });

            /** @noinspection PhpUnusedParameterInspection */
            $resolver->setNormalizer('translation', function (Options $options, $value) use ($translationResolver) {
                if (is_array($value)) {
                    return $translationResolver->resolve($value);
                }

                return $value;
            });


            // Event option
            $eventResolver = new OptionsResolver();
            $eventResolver
                ->setRequired(['class'])
                ->setDefaults([
                    'class'    => $this->defaultEventClass,
                    'priority' => 0,
                ])
                ->setAllowedTypes('class', 'string')
                ->setAllowedTypes('priority', 'int');

            /** @noinspection PhpUnusedParameterInspection */
            $resolver->setNormalizer('event', function (Options $options, $value) use ($eventResolver) {
                if (is_string($value)) {
                    $value = ['class' => $value];
                }

                $value = $eventResolver->resolve((array)$value);

                if (!is_subclass_of($value['class'], ResourceEventInterface::class)) {
                    throw new InvalidOptionsException(sprintf(
                        "Class '%s' must implements '%s'.",
                        $value['class'],
                        ResourceEventInterface::class
                    ));
                }

                return $value;
            });


            // Templates option
            /** @noinspection PhpUnusedParameterInspection */
            $resolver->setNormalizer('templates', function (Options $options, $value) {
                return $this->buildTemplateList($value);
            });


            $this->optionsResolver = $resolver;
        }

        return $this->optionsResolver;
    }
85546
public function validate() {
		parent::validate();

		if ($this->getEntity() === null) {
			throw new ValidationException("'entity' can't be null", 'entity', $this);
		}
		if ($this->getEntityStates() === null) {
			throw new ValidationException("'entityStates' can't be null", 'entityStates', $this);
		}
		if ($this->getUrl() === null) {
			throw new ValidationException("'url' can't be null", 'url', $this);
		}
	}
321673
public function validate() {

		if ($this->getCurrency() === null) {
			throw new ValidationException("'currency' can't be null", 'currency', $this);
		}
		if ($this->getProduct() === null) {
			throw new ValidationException("'product' can't be null", 'product', $this);
		}
		if ($this->getSubscription() === null) {
			throw new ValidationException("'subscription' can't be null", 'subscription', $this);
		}
	}
652717
public function validate() {
        foreach ($this->requiredfields as $key) {
            if (empty($this->{$key})) {
                throw new portfolio_format_leap2a_exception('leap2a_missingfield', 'portfolio', '', $key);
            }
        }
        if ($this->type == 'selection') {
            if (count($this->links) == 0) {
                throw new portfolio_format_leap2a_exception('leap2a_emptyselection', 'portfolio');
            }
            //TODO make sure we have a category with a scheme 'selection_type'
        }
    }
981304
public function processValidationErrors(array $validationErrors): void
    {
        if (empty($validationErrors)) {
            return;
        }

        $propertyPathGenerator = $this->propertyPathGenerator;
        foreach ($validationErrors as $i => $error) {
            $message = $error->getTranslatableMessage();
            /** @var \Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface $violationBuilder */
            $violationBuilder = $this->context->buildViolation($message instanceof Plural ? $message->plural : $message->message);
            $violationBuilder->setParameters($message->values);

            if ($propertyPathGenerator !== null) {
                $propertyPath = $propertyPathGenerator($i, $error->getTarget());
                if ($propertyPath) {
                    $violationBuilder->atPath($propertyPath);
                }
            }

            $violationBuilder->addViolation();
        }
    }
1347187
public function validate($value, Constraint $constraint)
    {
        if (!$value instanceof LanguageCreateStruct) {
            return;
        }

        try {
            $language = $this->languageService->loadLanguage($value->languageCode);
            if ($language->id == $value->getId()) {
                return;
            }

            $this->context->buildViolation($constraint->message)
                ->atPath('language_code')
                ->setParameter('%language_code%', $value->languageCode)
                ->addViolation();
        } catch (NotFoundException $e) {
            // Do nothing
        } catch (InvalidArgumentException $e) {
            // Do nothing
        }
    }
827103
protected function addExtraFormConstraintsNode()
    {
        $builder = new TreeBuilder();
        $node = $builder->root('constraints');

        $node
            ->defaultValue(array())
            ->useAttributeAsKey('id')
            ->prototype('array')
                ->children()
                    ->scalarNode('class')->isRequired()->end()
                    ->scalarNode('description')->defaultNull()->end()
                    ->arrayNode('extra_form_options')
                        ->defaultValue(array())
                        ->useAttributeAsKey('name')
                        ->prototype('array')
                            ->children()
                                ->scalarNode('extra_form_type')->isRequired()->end()
                                ->arrayNode('options')
                                    ->defaultValue(array())->useAttributeAsKey('id')->prototype('variable')->end()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $node;
    }
499461
public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof BankAccount) {
            throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\BankAccount');
        }

        if ($value === null || $value === '') {
            return;
        }

    /** @var \Symfony\Component\Form\Form $root */
        $root = $this->context->getRoot();

    /** @var \Generated\Shared\Transfer\QuoteTransfer $data */
        $data = $root->getData();

        $validationMessages = $this->validateBankAccount($data, $constraint);

        if (count($validationMessages) > 0) {
            foreach ($validationMessages as $validationMessage) {
                $this->buildViolation($validationMessage)
                ->addViolation();
            }
        }
    }
299723
public function parse()
    {
        $this->parser->parse($this->rawArguments);
        $this->parsed = true;
        $this->arguments = $this->parser->getArguments();
        $optionsShort = $this->parser->getOptionsShort();
        $optionsLong = $this->parser->getOptionsLong();
        $missongRequired = array();
        foreach ($this->optionDefinitions as $definition) {
            $value = $this->getOptionValue($definition);
            $short = $definition->getShort();
            $long = $definition->getLong();
            $optionsShort[$short] = $value;
            $optionsLong[$long] = $value;
            if ($definition->getRequired() && $value === null) {
                $parts = array();
                $parts[] = $short !== null ? '-' . $short : null;
                $parts[] = $long !== null ? '--' . $long : null;
                $missongRequired[] = implode('|', $parts);
            }
        }
        if (!empty($missongRequired)) {
            throw new GetoptException(
                'Missing required options: '
                . implode(', ', $missongRequired)
            );
        }
        $this->optionsShort = $optionsShort;
        $this->optionsLong = $optionsLong;
    }
980238
static void validateConfigurations(Configuration conf) throws ValidationException {
        if (null == conf.getHandlers()) {
            Log.error(
                    "Handler should not be null, One or more handler implementation shuld be configured in the configuration",
                    ErrorGuide.getGuide(ErrorGuide.EMPTY_HANDLERS));
            throw new ValidationException("Configuration error", ValidationException.VALIDATION_LEVEL_INVALID);
        }
        if (null == conf.getLayout()) {
            Log.error("Layout should not be null, A layout implementation shuld be configured in the configuration",
                    ErrorGuide.getGuide(ErrorGuide.EMPTY_LAYOUT));
            throw new ValidationException("Configuration error", ValidationException.VALIDATION_LEVEL_INVALID);
        }

    }
900582
public function validate()
    {
        if ($this->isWorkflowDispatch() && null === $this->getWorkflowRunType()) {
            $errMsg = 'workflowRunType not specified';
            throw new Exception\InvalidMetadataException($errMsg);
        }

        if ($this->isFlagRunPrepareData()) {
            if (null === $this->getPrepareDataMethod()) {
                $errMsg = 'prepareDataMethod not specified';
                throw new Exception\InvalidMetadataException($errMsg);
            }
            if (null === $this->getPrepareDataMethod()) {
                $errMsg = 'prepareDataMethod not specified';
                throw new Exception\InvalidMetadataException($errMsg);
            }
        }

        if ($this->getFlagHasConditions()) {
            if (0 === count($this->getConditions())) {
                $errMsg = 'empty conditions';
                throw new Exception\InvalidMetadataException($errMsg);
            }

            foreach ($this->getConditions() as $condition) {
                $condition->validate();
            }
        }
    }