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\Serializer\Mapping\Loader;
14 use Doctrine\Common\Annotations\Reader;
15 use Symfony\Component\Serializer\Annotation\Groups;
16 use Symfony\Component\Serializer\Exception\MappingException;
17 use Symfony\Component\Serializer\Mapping\AttributeMetadata;
18 use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
23 * @author Kévin Dunglas <dunglas@gmail.com>
25 class AnnotationLoader implements LoaderInterface
33 * @param Reader $reader
35 public function __construct(Reader $reader)
37 $this->reader = $reader;
43 public function loadClassMetadata(ClassMetadataInterface $classMetadata)
45 $reflectionClass = $classMetadata->getReflectionClass();
46 $className = $reflectionClass->name;
49 $attributesMetadata = $classMetadata->getAttributesMetadata();
51 foreach ($reflectionClass->getProperties() as $property) {
52 if (!isset($attributesMetadata[$property->name])) {
53 $attributesMetadata[$property->name] = new AttributeMetadata($property->name);
54 $classMetadata->addAttributeMetadata($attributesMetadata[$property->name]);
57 if ($property->getDeclaringClass()->name === $className) {
58 foreach ($this->reader->getPropertyAnnotations($property) as $groups) {
59 if ($groups instanceof Groups) {
60 foreach ($groups->getGroups() as $group) {
61 $attributesMetadata[$property->name]->addGroup($group);
70 foreach ($reflectionClass->getMethods() as $method) {
71 if ($method->getDeclaringClass()->name === $className) {
72 foreach ($this->reader->getMethodAnnotations($method) as $groups) {
73 if ($groups instanceof Groups) {
74 if (preg_match('/^(get|is|has|set)(.+)$/i', $method->name, $matches)) {
75 $attributeName = lcfirst($matches[2]);
77 if (isset($attributesMetadata[$attributeName])) {
78 $attributeMetadata = $attributesMetadata[$attributeName];
80 $attributesMetadata[$attributeName] = $attributeMetadata = new AttributeMetadata($attributeName);
81 $classMetadata->addAttributeMetadata($attributeMetadata);
84 foreach ($groups->getGroups() as $group) {
85 $attributeMetadata->addGroup($group);
88 throw new MappingException(sprintf('Groups on "%s::%s" cannot be added. Groups can only be added on methods beginning with "get", "is", "has" or "set".', $className, $method->name));