<?php
use Symfony\Component\Validator\ValidatorBuilder;
use Symfony\Component\Validator\Constraints as C;
use Symfony\Component\Validator\ConstraintViolationList;
use Doctrine\Common\Annotations\AnnotationRegistry;
$projectRootPath = '/path/to/project';
class Foo
{
/**
* @C\Range(min="1", max="100")
* @C\Type(type="int")
*/
public $number;
/**
* @C\Type(type="string")
*/
public $word;
}
// Validator uses Doctrine Annotation library
AnnotationRegistry::registerAutoloadNamespace(
'Symfony\Component\Validator\Constraints',
$projectRootPath . '/vendor/symfony/symfony/src'
);
$validator = (new ValidatorBuilder())
->enableAnnotationMapping()
->getValidator();
// create a valid Foo object
$validFoo = new Foo();
$validFoo->number = 5;
$validFoo->word = 'budgie';
// create an invalid Foo object
$invalidFoo = new Foo();
$invalidFoo->number = '105';
$invalidFoo->word = new ArrayObject();
$violationList = $validator->validate($validFoo);
echo get_violations($violationList);
$violationList = $validator->validate($invalidFoo);
echo get_violations($violationList);
function get_violations(ConstraintViolationList $violations) {
$out = '<pre>violation count: ' . count($violations) . PHP_EOL;
foreach($violations as $v) {
$out .= print_r($v->getMessage(), true) . PHP_EOL;
}
$out .= '</pre>';
return $out;
}
violation count: 0
violation count: 3 This value should be between "1" and "100". This value should be of type int. This value should be of type string.