Version 1
[yaffs-website] / vendor / symfony / serializer / Normalizer / GetSetMethodNormalizer.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Serializer\Normalizer;
13
14 use Symfony\Component\Serializer\Exception\CircularReferenceException;
15 use Symfony\Component\Serializer\Exception\LogicException;
16 use Symfony\Component\Serializer\Exception\RuntimeException;
17
18 /**
19  * Converts between objects with getter and setter methods and arrays.
20  *
21  * The normalization process looks at all public methods and calls the ones
22  * which have a name starting with get and take no parameters. The result is a
23  * map from property names (method name stripped of the get prefix and converted
24  * to lower case) to property values. Property values are normalized through the
25  * serializer.
26  *
27  * The denormalization first looks at the constructor of the given class to see
28  * if any of the parameters have the same name as one of the properties. The
29  * constructor is then called with all parameters or an exception is thrown if
30  * any required parameters were not present as properties. Then the denormalizer
31  * walks through the given map of property names to property values to see if a
32  * setter method exists for any of the properties. If a setter exists it is
33  * called with the property value. No automatic denormalization of the value
34  * takes place.
35  *
36  * @author Nils Adermann <naderman@naderman.de>
37  * @author Kévin Dunglas <dunglas@gmail.com>
38  */
39 class GetSetMethodNormalizer extends AbstractNormalizer
40 {
41     /**
42      * {@inheritdoc}
43      *
44      * @throws LogicException
45      * @throws CircularReferenceException
46      */
47     public function normalize($object, $format = null, array $context = array())
48     {
49         if ($this->isCircularReference($object, $context)) {
50             return $this->handleCircularReference($object);
51         }
52
53         $reflectionObject = new \ReflectionObject($object);
54         $reflectionMethods = $reflectionObject->getMethods(\ReflectionMethod::IS_PUBLIC);
55         $allowedAttributes = $this->getAllowedAttributes($object, $context, true);
56
57         $attributes = array();
58         foreach ($reflectionMethods as $method) {
59             if ($this->isGetMethod($method)) {
60                 $attributeName = lcfirst(substr($method->name, 0 === strpos($method->name, 'is') ? 2 : 3));
61                 if (in_array($attributeName, $this->ignoredAttributes)) {
62                     continue;
63                 }
64
65                 if (false !== $allowedAttributes && !in_array($attributeName, $allowedAttributes)) {
66                     continue;
67                 }
68
69                 $attributeValue = $method->invoke($object);
70                 if (isset($this->callbacks[$attributeName])) {
71                     $attributeValue = call_user_func($this->callbacks[$attributeName], $attributeValue);
72                 }
73                 if (null !== $attributeValue && !is_scalar($attributeValue)) {
74                     if (!$this->serializer instanceof NormalizerInterface) {
75                         throw new LogicException(sprintf('Cannot normalize attribute "%s" because injected serializer is not a normalizer', $attributeName));
76                     }
77
78                     $attributeValue = $this->serializer->normalize($attributeValue, $format, $context);
79                 }
80
81                 if ($this->nameConverter) {
82                     $attributeName = $this->nameConverter->normalize($attributeName);
83                 }
84
85                 $attributes[$attributeName] = $attributeValue;
86             }
87         }
88
89         return $attributes;
90     }
91
92     /**
93      * {@inheritdoc}
94      *
95      * @throws RuntimeException
96      */
97     public function denormalize($data, $class, $format = null, array $context = array())
98     {
99         $allowedAttributes = $this->getAllowedAttributes($class, $context, true);
100         $normalizedData = $this->prepareForDenormalization($data);
101
102         $reflectionClass = new \ReflectionClass($class);
103         $object = $this->instantiateObject($normalizedData, $class, $context, $reflectionClass, $allowedAttributes);
104
105         $classMethods = get_class_methods($object);
106         foreach ($normalizedData as $attribute => $value) {
107             if ($this->nameConverter) {
108                 $attribute = $this->nameConverter->denormalize($attribute);
109             }
110
111             $allowed = $allowedAttributes === false || in_array($attribute, $allowedAttributes);
112             $ignored = in_array($attribute, $this->ignoredAttributes);
113
114             if ($allowed && !$ignored) {
115                 $setter = 'set'.ucfirst($attribute);
116
117                 if (in_array($setter, $classMethods) && !$reflectionClass->getMethod($setter)->isStatic()) {
118                     $object->$setter($value);
119                 }
120             }
121         }
122
123         return $object;
124     }
125
126     /**
127      * {@inheritdoc}
128      */
129     public function supportsNormalization($data, $format = null)
130     {
131         return is_object($data) && !$data instanceof \Traversable && $this->supports(get_class($data));
132     }
133
134     /**
135      * {@inheritdoc}
136      */
137     public function supportsDenormalization($data, $type, $format = null)
138     {
139         return class_exists($type) && $this->supports($type);
140     }
141
142     /**
143      * Checks if the given class has any get{Property} method.
144      *
145      * @param string $class
146      *
147      * @return bool
148      */
149     private function supports($class)
150     {
151         $class = new \ReflectionClass($class);
152         $methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC);
153         foreach ($methods as $method) {
154             if ($this->isGetMethod($method)) {
155                 return true;
156             }
157         }
158
159         return false;
160     }
161
162     /**
163      * Checks if a method's name is get.* or is.*, and can be called without parameters.
164      *
165      * @param \ReflectionMethod $method the method to check
166      *
167      * @return bool whether the method is a getter or boolean getter
168      */
169     private function isGetMethod(\ReflectionMethod $method)
170     {
171         $methodLength = strlen($method->name);
172
173         return
174             !$method->isStatic() &&
175             (
176                 ((0 === strpos($method->name, 'get') && 3 < $methodLength) ||
177                 (0 === strpos($method->name, 'is') && 2 < $methodLength)) &&
178                 0 === $method->getNumberOfRequiredParameters()
179             )
180         ;
181     }
182 }