Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Normalizer/GetSetMethodNormalizer.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
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\PropertyAccess\Exception\UninitializedPropertyException;
15 use Symfony\Component\Serializer\Annotation\Ignore as LegacyIgnore;
16 use Symfony\Component\Serializer\Attribute\Ignore;
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 <[email protected]>
37 * @author Kévin Dunglas <[email protected]>
38 */
39 final class GetSetMethodNormalizer extends AbstractObjectNormalizer
40 {
41 private static $reflectionCache = [];
42 private static array $setterAccessibleCache = [];
43
44 public function getSupportedTypes(?string $format): array
45 {
46 return ['object' => true];
47 }
48
49 public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
50 {
51 return parent::supportsNormalization($data, $format) && $this->supports($data::class, true);
52 }
53
54 public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
55 {
56 return parent::supportsDenormalization($data, $type, $format) && $this->supports($type, false);
57 }
58
59 /**
60 * Checks if the given class has any getter or setter method.
61 */
62 private function supports(string $class, bool $readAttributes): bool
63 {
64 if ($this->classDiscriminatorResolver?->getMappingForClass($class)) {
65 return true;
66 }
67
68 if (!isset(self::$reflectionCache[$class])) {
69 self::$reflectionCache[$class] = new \ReflectionClass($class);
70 }
71
72 $reflection = self::$reflectionCache[$class];
73
74 foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
75 if ($readAttributes ? $this->isGetMethod($reflectionMethod) : $this->isSetMethod($reflectionMethod)) {
76 return true;
77 }
78 }
79
80 return false;
81 }
82
83 /**
84 * Checks if a method's name matches /^(get|is|has|can).+$/ and can be called non-statically without parameters.
85 */
86 private function isGetMethod(\ReflectionMethod $method): bool
87 {
88 return !$method->isStatic()
89 && !($method->getAttributes(Ignore::class) || $method->getAttributes(LegacyIgnore::class))
90 && !$method->getNumberOfRequiredParameters()
91 && !\in_array((string) $method->getReturnType(), ['void', 'never'], true)
92 && ((2 < ($methodLength = \strlen($method->name)) && str_starts_with($method->name, 'is') && !ctype_lower($method->name[2]))
93 || (3 < $methodLength && (str_starts_with($method->name, 'has') || str_starts_with($method->name, 'get') || str_starts_with($method->name, 'can')) && !ctype_lower($method->name[3]))
94 );
95 }
96
97 /**
98 * Checks if a method's name matches /^set.+$/ and can be called non-statically with one parameter.
99 */
100 private function isSetMethod(\ReflectionMethod $method): bool
101 {
102 return !$method->isStatic()
103 && !$method->getAttributes(Ignore::class)
104 && 0 < $method->getNumberOfParameters()
105 && 3 < \strlen($method->name)
106 && str_starts_with($method->name, 'set')
107 && !ctype_lower($method->name[3])
108 ;
109 }
110
111 protected function extractAttributes(object $object, ?string $format = null, array $context = []): array
112 {
113 $reflectionObject = new \ReflectionObject($object);
114 $reflectionMethods = $reflectionObject->getMethods(\ReflectionMethod::IS_PUBLIC);
115
116 $attributes = [];
117 foreach ($reflectionMethods as $method) {
118 if (!$this->isGetMethod($method)) {
119 continue;
120 }
121
122 $attributeName = lcfirst(substr($method->name, str_starts_with($method->name, 'is') ? 2 : 3));
123
124 if ($this->isAllowedAttribute($object, $attributeName, $format, $context)) {
125 $attributes[] = $attributeName;
126 }
127 }
128
129 return $attributes;
130 }
131
132 protected function getAttributeValue(object $object, string $attribute, ?string $format = null, array $context = []): mixed
133 {
134 try {
135 $getter = 'get'.$attribute;
136 if (method_exists($object, $getter) && \is_callable([$object, $getter])) {
137 return $object->$getter();
138 }
139
140 $isser = 'is'.$attribute;
141 if (method_exists($object, $isser) && \is_callable([$object, $isser])) {
142 return $object->$isser();
143 }
144
145 $haser = 'has'.$attribute;
146 if (method_exists($object, $haser) && \is_callable([$object, $haser])) {
147 return $object->$haser();
148 }
149
150 $caner = 'can'.$attribute;
151 if (method_exists($object, $caner) && \is_callable([$object, $caner])) {
152 return $object->$caner();
153 }
154 } catch (\Error $e) {
155 if (str_starts_with($e->getMessage(), 'Typed property') && str_ends_with($e->getMessage(), 'must not be accessed before initialization')) {
156 throw new UninitializedPropertyException(\sprintf('The property "%s::$%s" is not initialized.', $object::class, $attribute), 0, $e);
157 }
158 throw $e;
159 }
160
161 return null;
162 }
163
164 protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []): void
165 {
166 $setter = 'set'.$attribute;
167 $key = $object::class.':'.$setter;
168
169 if (!isset(self::$setterAccessibleCache[$key])) {
170 self::$setterAccessibleCache[$key] = method_exists($object, $setter) && \is_callable([$object, $setter]) && !(new \ReflectionMethod($object, $setter))->isStatic();
171 }
172
173 if (self::$setterAccessibleCache[$key]) {
174 $object->$setter($value);
175 }
176 }
177
178 protected function isAllowedAttribute($classOrObject, string $attribute, ?string $format = null, array $context = []): bool
179 {
180 if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
181 return false;
182 }
183
184 $class = \is_object($classOrObject) ? $classOrObject::class : $classOrObject;
185
186 if ($this->classDiscriminatorResolver?->getMappingForMappedObject($classOrObject)?->getTypeProperty() === $attribute) {
187 return true;
188 }
189
190 if (!isset(self::$reflectionCache[$class])) {
191 self::$reflectionCache[$class] = new \ReflectionClass($class);
192 }
193
194 $reflection = self::$reflectionCache[$class];
195
196 if ($context['_read_attributes'] ?? true) {
197 foreach (['get', 'is', 'has', 'can'] as $getterPrefix) {
198 $getter = $getterPrefix.$attribute;
199 $reflectionMethod = $reflection->hasMethod($getter) ? $reflection->getMethod($getter) : null;
200 if ($reflectionMethod && $this->isGetMethod($reflectionMethod)) {
201 return true;
202 }
203 }
204
205 return false;
206 }
207
208 $setter = 'set'.$attribute;
209 if ($reflection->hasMethod($setter) && $this->isSetMethod($reflection->getMethod($setter))) {
210 return true;
211 }
212
213 $constructor = $reflection->getConstructor();
214
215 if ($constructor && $constructor->isPublic()) {
216 foreach ($constructor->getParameters() as $parameter) {
217 if ($parameter->getName() === $attribute) {
218 return true;
219 }
220 }
221 }
222
223 return false;
224 }
225 }