<?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\NotBlank(payload={"severity"="info"})
* @C\NotNull(payload={"severity"="error"})
*/
public $word;
}
// Validator uses Doctrine Annotation library
AnnotationRegistry::registerAutoloadNamespace(
'Symfony\Component\Validator\Constraints',
$projectRootPath . '/vendor/symfony/symfony/src'
);
$echoLog = function($violationList) {
foreach ($violationList as $violation) {
$constraint = $violation->getConstraint();
if (isset($constraint->payload['severity']) && 'error' === $constraint->payload['severity']) {
echo $constraint->message.PHP_EOL;
}
}
};
$validator = (new ValidatorBuilder())
->enableAnnotationMapping()
->getValidator();
$foo = new Foo();
echo '<b>Value is null.</b>'.PHP_EOL;
$violationList = $validator->validate($foo);
$echoLog($violationList);
echo '<b>Value is blank.</b>'.PHP_EOL;
$foo->word = '';
$violationList = $validator->validate($foo);
$echoLog($violationList);