First of all, you need to know that Symfony2 validators are not ready for this easily. It took me some time and some reading of the source of Symfony2 to get a working solution for your case, and my solution is not so natural.
I created a class that accepts a validator, your array and your yaml configuration file so you can do what you expect. This class extends Symfony’s YamlFileLoader to access the parseNodes protected method: this isn’t beautiful, but the only way I have found converting a custom Yaml configuration file to an array of Constraint objects.
So here we are. I give you my code, you will need to replace some namespaces according to your own context.
First create a controller for our demo:
public function indexAction() { // We create a sample validation file for the demo $demo = <<< EOT name: - NotBlank: ~ - MinLength: { limit: 3 } - MaxLength: { limit: 10 } date: - NotBlank: ~ - Regex: "/^[0-9]{4}\-[0-9]{2}$/" price: - Min: 0 EOT; file_put_contents("/tmp/test.yml", $demo); // We create your array to validate $product = array (); $product['name'] = 'A book'; $product['date'] = '2012-09'; $product['price'] = '21.5'; $validator = $this->get('validator'); $service = new \Fuz\TestsBundle\Services\ArrayValidator($validator, $product, "/tmp/test.yml"); $errors = $service->validate(); echo '<pre>'; var_dump($errors); die(); return $this->render('FuzTestsBundle:Default:index.html.twig'); }
Then create a class called ArrayValidator.php. Again, take care of the namespace.
<?php namespace Fuz\TestsBundle\Services; use Symfony\Component\Validator\ValidatorInterface; use Symfony\Component\Yaml\Parser; use Symfony\Component\Validator\Mapping\Loader\YamlFileLoader; class ArrayValidator extends YamlFileLoader { private $validator; private $array; private $validationFile; public function __construct(ValidatorInterface $validator, array $array = array(), $validationFile) { $this->validator = $validator; $this->array = $array; $this->validationFile = $validationFile; } public function validate() { $yaml = file_get_contents($this->validationFile);
Finally, check it with different values in the $ product array.
Default:
$product = array (); $product['name'] = 'A book'; $product['date'] = '2012-09'; $product['price'] = '21.5';
The following is displayed:
array(3) { ["name"]=> array(0) { } ["date"]=> array(0) { } ["price"]=> array(0) { } }
If we change the values to:
$product = array (); $product['name'] = 'A very interesting book'; $product['date'] = '2012-09-03'; $product['price'] = '-21.5';
You'll get:
array(3) { ["name"]=> array(1) { [0]=> string(61) "This value is too long. It should have 10 characters or less." } ["date"]=> array(1) { [0]=> string(24) "This value is not valid." } ["price"]=> array(1) { [0]=> string(31) "This value should be 0 or more." } }
Hope this helps.