Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like ItemNormalizer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ItemNormalizer, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
37 | final class ItemNormalizer extends AbstractItemNormalizer |
||
38 | { |
||
39 | use ContextTrait; |
||
40 | use ClassInfoTrait; |
||
41 | |||
42 | const FORMAT = 'jsonapi'; |
||
43 | |||
44 | private $componentsCache = []; |
||
45 | |||
46 | private $resourceMetadataFactory; |
||
47 | |||
48 | private $itemDataProvider; |
||
49 | |||
50 | View Code Duplication | public function __construct( |
|
|
|||
51 | PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, |
||
52 | PropertyMetadataFactoryInterface $propertyMetadataFactory, |
||
53 | IriConverterInterface $iriConverter, |
||
54 | ResourceClassResolverInterface $resourceClassResolver, |
||
55 | PropertyAccessorInterface $propertyAccessor = null, |
||
56 | NameConverterInterface $nameConverter = null, |
||
57 | ResourceMetadataFactoryInterface $resourceMetadataFactory, |
||
58 | ItemDataProviderInterface $itemDataProvider |
||
59 | ) { |
||
60 | parent::__construct( |
||
61 | $propertyNameCollectionFactory, |
||
62 | $propertyMetadataFactory, |
||
63 | $iriConverter, |
||
64 | $resourceClassResolver, |
||
65 | $propertyAccessor, |
||
66 | $nameConverter |
||
67 | ); |
||
68 | |||
69 | $this->resourceMetadataFactory = $resourceMetadataFactory; |
||
70 | $this->itemDataProvider = $itemDataProvider; |
||
71 | } |
||
72 | |||
73 | /** |
||
74 | * {@inheritdoc} |
||
75 | */ |
||
76 | public function supportsNormalization($data, $format = null) |
||
77 | { |
||
78 | return self::FORMAT === $format && parent::supportsNormalization($data, $format); |
||
79 | } |
||
80 | |||
81 | /** |
||
82 | * {@inheritdoc} |
||
83 | */ |
||
84 | public function normalize($object, $format = null, array $context = []) |
||
85 | { |
||
86 | $context['cache_key'] = $this->getCacheKey($format, $context); |
||
87 | |||
88 | // Get and populate attributes data |
||
89 | $objectAttributesData = parent::normalize($object, $format, $context); |
||
90 | |||
91 | if (!is_array($objectAttributesData)) { |
||
92 | return $objectAttributesData; |
||
93 | } |
||
94 | |||
95 | // Get and populate identifier if existent |
||
96 | $identifier = $this->getIdentifierFromItem($object); |
||
97 | |||
98 | // Get and populate item type |
||
99 | $resourceClass = $this->resourceClassResolver->getResourceClass( |
||
100 | $object, |
||
101 | $context['resource_class'] ?? null, |
||
102 | true |
||
103 | ); |
||
104 | $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass); |
||
105 | |||
106 | // Get and populate relations |
||
107 | $components = $this->getComponents($object, $format, $context); |
||
108 | $objectRelationshipsData = $this->getPopulatedRelations( |
||
109 | $object, |
||
110 | $format, |
||
111 | $context, |
||
112 | $components |
||
113 | ); |
||
114 | |||
115 | $item = [ |
||
116 | // The id attribute must be a string |
||
117 | // See: http://jsonapi.org/format/#document-resource-object-identification |
||
118 | 'id' => (string) $identifier, |
||
119 | 'type' => $resourceMetadata->getShortName(), |
||
120 | ]; |
||
121 | |||
122 | if ($objectAttributesData) { |
||
123 | $item['attributes'] = $objectAttributesData; |
||
124 | } |
||
125 | |||
126 | if ($objectRelationshipsData) { |
||
127 | $item['relationships'] = $objectRelationshipsData; |
||
128 | } |
||
129 | |||
130 | return ['data' => $item]; |
||
131 | } |
||
132 | |||
133 | /** |
||
134 | * {@inheritdoc} |
||
135 | */ |
||
136 | public function supportsDenormalization($data, $type, $format = null) |
||
140 | |||
141 | /** |
||
142 | * {@inheritdoc} |
||
143 | */ |
||
144 | public function denormalize($data, $class, $format = null, array $context = []) |
||
145 | { |
||
146 | // Avoid issues with proxies if we populated the object |
||
147 | View Code Duplication | if (isset($data['data']['id']) && !isset($context['object_to_populate'])) { |
|
148 | if (isset($context['api_allow_update']) && true !== $context['api_allow_update']) { |
||
149 | throw new InvalidArgumentException('Update is not allowed for this operation.'); |
||
150 | } |
||
151 | |||
152 | $context['object_to_populate'] = $this->iriConverter->getItemFromIri( |
||
153 | $data['data']['id'], |
||
154 | $context + ['fetch_data' => false] |
||
155 | ); |
||
156 | } |
||
157 | |||
158 | // Merge attributes and relations previous to apply parents denormalizing |
||
159 | $dataToDenormalize = array_merge( |
||
160 | $data['data']['attributes'] ?? [], |
||
161 | $data['data']['relationships'] ?? [] |
||
162 | ); |
||
163 | |||
164 | return parent::denormalize( |
||
165 | $dataToDenormalize, |
||
166 | $class, |
||
167 | $format, |
||
168 | $context |
||
169 | ); |
||
170 | } |
||
171 | |||
172 | /** |
||
173 | * {@inheritdoc} |
||
174 | */ |
||
175 | protected function getAttributes($object, $format, array $context) |
||
176 | { |
||
177 | return $this->getComponents($object, $format, $context)['attributes']; |
||
178 | } |
||
179 | |||
180 | /** |
||
181 | * Gets JSON API components of the resource: attributes, relationships, meta and links. |
||
182 | * |
||
183 | * @param object $object |
||
184 | * @param string|null $format |
||
185 | * @param array $context |
||
186 | * |
||
187 | * @return array |
||
188 | */ |
||
189 | private function getComponents($object, string $format = null, array $context) |
||
190 | { |
||
191 | if (isset($this->componentsCache[$context['cache_key']])) { |
||
192 | return $this->componentsCache[$context['cache_key']]; |
||
193 | } |
||
194 | |||
195 | $attributes = parent::getAttributes($object, $format, $context); |
||
196 | |||
197 | $options = $this->getFactoryOptions($context); |
||
198 | |||
199 | $typeShortName = $className = ''; |
||
200 | |||
201 | $components = [ |
||
202 | 'links' => [], |
||
203 | 'relationships' => [], |
||
204 | 'attributes' => [], |
||
205 | 'meta' => [], |
||
206 | ]; |
||
207 | |||
208 | foreach ($attributes as $attribute) { |
||
209 | $propertyMetadata = $this |
||
210 | ->propertyMetadataFactory |
||
211 | ->create($context['resource_class'], $attribute, $options); |
||
212 | |||
213 | $type = $propertyMetadata->getType(); |
||
214 | $isOne = $isMany = false; |
||
215 | |||
216 | if (null !== $type) { |
||
217 | View Code Duplication | if ($type->isCollection()) { |
|
218 | $valueType = $type->getCollectionValueType(); |
||
219 | |||
220 | $isMany = null !== $valueType |
||
221 | && ($className = $valueType->getClassName()) |
||
222 | && $this->resourceClassResolver->isResourceClass($className); |
||
223 | } else { |
||
224 | $className = $type->getClassName(); |
||
225 | |||
226 | $isOne = null !== $className |
||
227 | && $this->resourceClassResolver->isResourceClass($className); |
||
228 | } |
||
229 | |||
230 | $typeShortName = ''; |
||
231 | |||
232 | if ($className && $this->resourceClassResolver->isResourceClass($className)) { |
||
233 | $typeShortName = $this |
||
234 | ->resourceMetadataFactory |
||
235 | ->create($className) |
||
236 | ->getShortName(); |
||
237 | } |
||
238 | } |
||
239 | |||
240 | if (!$isOne && !$isMany) { |
||
241 | $components['attributes'][] = $attribute; |
||
242 | |||
243 | continue; |
||
244 | } |
||
245 | |||
246 | $relation = [ |
||
247 | 'name' => $attribute, |
||
248 | 'type' => $typeShortName, |
||
249 | 'cardinality' => $isOne ? 'one' : 'many', |
||
250 | ]; |
||
251 | |||
252 | $components['relationships'][] = $relation; |
||
253 | } |
||
254 | |||
255 | return $this->componentsCache[$context['cache_key']] = $components; |
||
256 | } |
||
257 | |||
258 | /** |
||
259 | * Populates links and relationships keys. |
||
260 | * |
||
261 | * @param array $data |
||
262 | * @param object $object |
||
263 | * @param string|null $format |
||
264 | * @param array $context |
||
265 | * @param array $components |
||
266 | * @param string $type |
||
267 | * |
||
268 | * @return array |
||
269 | */ |
||
270 | private function getPopulatedRelations( |
||
271 | $object, |
||
272 | string $format = null, |
||
273 | array $context, |
||
274 | array $components, |
||
275 | string $type = 'relationships' |
||
276 | ): array { |
||
277 | $data = []; |
||
278 | |||
279 | $identifier = ''; |
||
280 | foreach ($components[$type] as $relationshipDataArray) { |
||
281 | $relationshipName = $relationshipDataArray['name']; |
||
282 | |||
283 | $attributeValue = $this->getAttributeValue( |
||
284 | $object, |
||
285 | $relationshipName, |
||
286 | $format, |
||
287 | $context |
||
288 | ); |
||
289 | |||
290 | if ($this->nameConverter) { |
||
291 | $relationshipName = $this->nameConverter->normalize($relationshipName); |
||
292 | } |
||
293 | |||
294 | if (!$attributeValue) { |
||
295 | continue; |
||
296 | } |
||
297 | |||
298 | $data[$relationshipName] = [ |
||
299 | 'data' => [], |
||
300 | ]; |
||
301 | |||
302 | // Many to one relationship |
||
303 | if ('one' === $relationshipDataArray['cardinality']) { |
||
304 | $data[$relationshipName] = $attributeValue; |
||
305 | |||
306 | continue; |
||
307 | } |
||
308 | |||
309 | // Many to many relationship |
||
310 | foreach ($attributeValue as $attributeValueElement) { |
||
311 | if (!isset($attributeValueElement['data'])) { |
||
312 | throw new RuntimeException(sprintf( |
||
313 | 'Expected \'data\' attribute in collection for attribute \'%s\'', |
||
314 | $relationshipName |
||
315 | )); |
||
316 | } |
||
317 | |||
318 | $data[$relationshipName]['data'][] = $attributeValueElement['data']; |
||
319 | } |
||
320 | } |
||
321 | |||
322 | return $data; |
||
323 | } |
||
324 | |||
325 | /** |
||
326 | * Gets the IRI of the given relation. |
||
327 | * |
||
328 | * @param array|string $rel |
||
329 | * |
||
330 | * @return string |
||
331 | */ |
||
332 | private function getRelationIri($rel): string |
||
333 | { |
||
334 | return $rel['links']['self'] ?? $rel; |
||
335 | } |
||
336 | |||
337 | /** |
||
338 | * Gets the cache key to use. |
||
339 | * |
||
340 | * @param string|null $format |
||
341 | * @param array $context |
||
342 | * |
||
343 | * @return bool|string |
||
344 | */ |
||
345 | View Code Duplication | private function getCacheKey(string $format = null, array $context) |
|
354 | |||
355 | /** |
||
356 | * Denormalizes a resource linkage relation. |
||
357 | * |
||
358 | * See: http://jsonapi.org/format/#document-resource-object-linkage |
||
359 | * |
||
360 | * @param string $attributeName [description] |
||
361 | * @param PropertyMetadata $propertyMetadata [description] |
||
362 | * @param string $className [description] |
||
363 | * @param [type] $data [description] |
||
364 | * @param string|null $format [description] |
||
365 | * @param array $context [description] |
||
366 | * |
||
367 | * @return [type] [description] |
||
368 | */ |
||
369 | protected function denormalizeRelation( |
||
414 | |||
415 | /** |
||
416 | * Normalizes a relation as resource linkage relation. |
||
417 | * |
||
418 | * See: http://jsonapi.org/format/#document-resource-object-linkage |
||
419 | * |
||
420 | * For example, it may return the following array: |
||
421 | * |
||
422 | * [ |
||
423 | * 'data' => [ |
||
424 | * 'type' => 'dummy', |
||
425 | * 'id' => '1' |
||
426 | * ] |
||
427 | * ] |
||
428 | * |
||
429 | * @param PropertyMetadata $propertyMetadata |
||
430 | * @param mixed $relatedObject |
||
431 | * @param string $resourceClass |
||
432 | * @param string|null $format |
||
433 | * @param array $context |
||
434 | * |
||
435 | * @return string|array |
||
436 | */ |
||
437 | protected function normalizeRelation( |
||
459 | |||
460 | private function getIdentifierFromItem($item) |
||
473 | |||
474 | /** |
||
475 | * Find identifiers from an Item (Object). |
||
476 | * |
||
477 | * Taken from ApiPlatform\Core\Bridge\Symfony\Routing\IriConverter |
||
478 | * |
||
479 | * @param object $item |
||
480 | * |
||
481 | * @throws RuntimeException |
||
482 | * |
||
483 | * @return array |
||
484 | */ |
||
485 | View Code Duplication | private function getIdentifiersFromItem($item): array |
|
554 | } |
||
555 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.