public function validate($model) { $builder = new ValidatorBuilder(); $builder->setTranslator($this->service->getTranslator()); $validator = $builder->getValidator(); $validations = $this->getValidations(); $this->violations = new ConstraintViolationList(); foreach ($validations as $column => $validation) { $method = 'get' . NameUtils::toStudlyCase($column); if (method_exists($model, $method)) { $value = $model->{$method}(); $constraints = []; foreach ($validation as $options) { $name = $options['constraint']; unset($options['constraint']); $constraints[] = $this->getConstraint($name, $options); } $violations = $validator->validate($value, $constraints); $this->violations->addAll($violations); } } return (bool) (!(count($this->violations) > 0)); }
require_once __DIR__ . '/_common.php'; use Symfony\Component\Validator\ValidatorBuilder; use Symfony\Component\Translation\Translator; use Symfony\Component\Validator\Constraints\Collection; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Validator\Constraints\Type; use Symfony\Component\Validator\Constraints\Range; use Symfony\Component\Validator\Constraints\Choice; use Symfony\Component\Validator\Constraints\CardScheme; use Symfony\Component\Validator\Constraints\DateTime; // see http://symfony.com/doc/current/reference/constraints/Collection.html // builder which creates Validator as we need $builder = new ValidatorBuilder(); $builder->setTranslator(new Translator('cs_CZ')); $validator = $builder->getValidator(); // Example no. 1 // ------------- // // This example shows that Collection constrains checks // if array field fulfill our constraints or // if some array fields are missing or // if there are some extra fields in validated array echo "Example no. 1: \n"; $inputData = ['name' => '', 'age' => '', 'isActive' => '', 'createdAt' => '']; $violations = $validator->validate($inputData, new Collection(['name' => new NotBlank(), 'email' => new Email(['groups' => 'test'])]), ['test']); App\Utils::printViolations($violations); // Example no. 2 // ------------- //