4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Mapping\Loader;
14 use Doctrine\Common\Annotations\Reader;
15 use Symfony\Component\Validator\Constraint;
16 use Symfony\Component\Validator\Constraints\Callback;
17 use Symfony\Component\Validator\Constraints\GroupSequence;
18 use Symfony\Component\Validator\Constraints\GroupSequenceProvider;
19 use Symfony\Component\Validator\Exception\MappingException;
20 use Symfony\Component\Validator\Mapping\ClassMetadata;
23 * Loads validation metadata using a Doctrine annotation {@link Reader}.
25 * @author Bernhard Schussek <bschussek@gmail.com>
27 class AnnotationLoader implements LoaderInterface
31 public function __construct(Reader $reader)
33 $this->reader = $reader;
39 public function loadClassMetadata(ClassMetadata $metadata)
41 $reflClass = $metadata->getReflectionClass();
42 $className = $reflClass->name;
45 foreach ($this->reader->getClassAnnotations($reflClass) as $constraint) {
46 if ($constraint instanceof GroupSequence) {
47 $metadata->setGroupSequence($constraint->groups);
48 } elseif ($constraint instanceof GroupSequenceProvider) {
49 $metadata->setGroupSequenceProvider(true);
50 } elseif ($constraint instanceof Constraint) {
51 $metadata->addConstraint($constraint);
57 foreach ($reflClass->getProperties() as $property) {
58 if ($property->getDeclaringClass()->name === $className) {
59 foreach ($this->reader->getPropertyAnnotations($property) as $constraint) {
60 if ($constraint instanceof Constraint) {
61 $metadata->addPropertyConstraint($property->name, $constraint);
69 foreach ($reflClass->getMethods() as $method) {
70 if ($method->getDeclaringClass()->name === $className) {
71 foreach ($this->reader->getMethodAnnotations($method) as $constraint) {
72 if ($constraint instanceof Callback) {
73 $constraint->callback = $method->getName();
75 $metadata->addConstraint($constraint);
76 } elseif ($constraint instanceof Constraint) {
77 if (preg_match('/^(get|is|has)(.+)$/i', $method->name, $matches)) {
78 $metadata->addGetterMethodConstraint(lcfirst($matches[2]), $matches[0], $constraint);
80 throw new MappingException(sprintf('The constraint on "%s::%s" cannot be added. Constraints can only be added on methods beginning with "get", "is" or "has".', $className, $method->name));