DataLinksHelper   C
last analyzed

Complexity

Total Complexity 73

Size/Duplication

Total Lines 429
Duplicated Lines 3.26 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 19
Bugs 2 Features 3
Metric Value
wmc 73
c 19
b 2
f 3
lcom 1
cbo 5
dl 14
loc 429
rs 5.5447

14 Methods

Rating   Name   Duplication   Size   Complexity  
C setResponseDataLinks() 0 45 11
C setResponseDataRelationship() 0 66 17
A addRelationshipData() 14 14 2
B relationshipLinksSelf() 0 29 3
C setResponseDataRelationshipSelfLinks() 0 29 8
D relationshipLinksRelated() 0 28 9
B buildUrl() 0 29 6
C secondPassBuildUrl() 0 29 8
A toCamelCase() 0 6 1
A toLowerFirstCamelCase() 0 7 1
A toUnderScore() 0 6 1
A camelCaseToUnderscore() 0 10 1
A underscoreToCamelCase() 0 4 1
A removeArraysFromKeyValueReplacement() 0 14 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

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 Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DataLinksHelper 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 DataLinksHelper, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Author: Nil Portugués Calderó <[email protected]>
5
 * Date: 7/25/15
6
 * Time: 9:54 PM.
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace NilPortugues\Api\JsonApi\Helpers;
12
13
use NilPortugues\Api\JsonApi\JsonApiTransformer;
14
use NilPortugues\Api\Transformer\Helpers\RecursiveDeleteHelper;
15
use NilPortugues\Api\Transformer\Helpers\RecursiveFormatterHelper;
16
use NilPortugues\Serializer\Serializer;
17
18
/**
19
 * Class DataLinksHelper.
20
 */
21
class DataLinksHelper
22
{
23
    /**
24
     * @param \NilPortugues\Api\Mapping\Mapping[] $mappings
25
     * @param array                               $value
26
     *
27
     * @return array
28
     */
29
    public static function setResponseDataLinks(array &$mappings, array &$value)
30
    {
31
        $data = [];
32
        $type = $value[Serializer::CLASS_IDENTIFIER_KEY];
33
34
        if (\is_scalar($type) && !empty($mappings[$type])) {
35
            $copy = $value;
36
            RecursiveFormatterHelper::formatScalarValues($copy);
37
            if (!empty($copy[Serializer::CLASS_IDENTIFIER_KEY])) {
38
                unset($copy[Serializer::CLASS_IDENTIFIER_KEY]);
39
            }
40
41
            $idProperties = array_keys($copy);
42
            foreach ($idProperties as &$property) {
43
                $property = sprintf('{%s}', $property);
44
            }
45
            $idValues = array_values($copy);
46
47
            $selfLink = $mappings[$type]->getResourceUrl();
48
49
            if (!empty($selfLink)) {
50
                $url = self::buildUrl($mappings, $idProperties, $idValues, $selfLink, $type);
51
52
                if ($url !== $selfLink) {
53
                    $data[JsonApiTransformer::LINKS_KEY][JsonApiTransformer::SELF_LINK][JsonApiTransformer::LINKS_HREF] = $url;
54
                }
55
            }
56
57
            self::removeArraysFromKeyValueReplacement($idProperties, $idValues);
58
59
            foreach ($mappings[$type]->getUrls() as $name => $url) {
60
                if (is_array($url) && !empty($url['name'])) {
61
                    $url = $url['name'];
62
                }
63
64
                $newUrl = \str_replace($idProperties, $idValues, $url);
65
66
                if ($newUrl !== $url) {
67
                    $data[JsonApiTransformer::LINKS_KEY][$name][JsonApiTransformer::LINKS_HREF] = $newUrl;
68
                }
69
            }
70
        }
71
72
        return $data;
73
    }
74
75
    /**
76
     * @param \NilPortugues\Api\Mapping\Mapping[] $mappings
77
     * @param array                               $array
78
     * @param array                               $parent
79
     *
80
     * @return array
81
     */
82
    public static function setResponseDataRelationship(array &$mappings, array &$array, array $parent)
83
    {
84
        $data = [JsonApiTransformer::RELATIONSHIPS_KEY => []];
85
86
        foreach ($array as $propertyName => $value) {
87
            if (\is_array($value)) {
88
                self::addRelationshipData($mappings, $parent, $value, $propertyName, $data);
89
                if (\array_key_exists(Serializer::MAP_TYPE, $value)) {
90
                    $newData = [];
91
                    foreach ($value[Serializer::SCALAR_VALUE] as $d) {
92
                        self::addRelationshipData($mappings, $parent, $d, $propertyName, $newData);
93
94
                        if (!empty($d[Serializer::CLASS_IDENTIFIER_KEY])) {
95
                            $type = $d[Serializer::CLASS_IDENTIFIER_KEY];
96
97
                            if (!in_array($propertyName, RecursiveFormatterHelper::getIdProperties($mappings, $type), true)) {
98
                                $parentType = $d[Serializer::CLASS_IDENTIFIER_KEY];
99
100
                                list($idValues, $idProperties) = RecursiveFormatterHelper::getIdPropertyAndValues(
101
                                    $mappings,
102
                                    $d,
103
                                    $parentType
104
                                );
105
106
                                if (!empty($mappings[$parentType]) && !empty($selfLink = $mappings[$parentType]->getRelationshipSelfUrl($propertyName))) {
107
                                    $href = \str_replace($idProperties, $idValues, $selfLink);
108
                                    if ($selfLink != $href) {
109
                                        $propertyNameKey = DataAttributesHelper::transformToValidMemberName($propertyName);
110
                                        $propertyNameKey = self::camelCaseToUnderscore($propertyNameKey);
111
112
                                        $newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyNameKey][JsonApiTransformer::LINKS_KEY][JsonApiTransformer::SELF_LINK][JsonApiTransformer::LINKS_HREF] = $href;
113
                                    }
114
                                }
115
                            }
116
                        }
117
118
                        if (!empty($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName])) {
119
                            $propertyNameKey = DataAttributesHelper::transformToValidMemberName($propertyName);
120
                            $propertyNameKey = self::camelCaseToUnderscore($propertyNameKey);
121
122
                            if (!empty($d[Serializer::CLASS_IDENTIFIER_KEY])) {
123
                                $type = $d[Serializer::CLASS_IDENTIFIER_KEY];
124
                                $parentType = $parent[Serializer::CLASS_IDENTIFIER_KEY];
125
126
                                //Removes relationships related to the current resource if filtering include resources has been set.
127
                                if (!empty($mappings[$parentType]) && !empty($mappings[$parentType]->isFilteringIncludedResources())) {
128
                                    foreach ($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName] as $position => $includedResource) {
129
                                        if (false === in_array($type, $mappings[$parentType]->getIncludedResources(), true)) {
130
                                            unset($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName][$position]);
131
                                        }
132
                                    }
133
                                }
134
135
                                $newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName] = array_filter($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName]);
136
                                if (!empty($newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName])) {
137
                                    $data[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyNameKey][] = $newData[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName];
138
                                }
139
                            }
140
                        }
141
                    }
142
                }
143
            }
144
        }
145
146
        return (array) \array_filter($data);
147
    }
148
149
    /**
150
     * @param array $mappings
151
     * @param array $parent
152
     * @param       $value
153
     * @param       $propertyName
154
     * @param       $data
155
     */
156 View Code Duplication
    protected static function addRelationshipData(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
157
        array &$mappings,
158
        array &$parent,
159
        &$value,
160
        &$propertyName,
161
        &$data
162
    ) {
163
        if (\array_key_exists(Serializer::CLASS_IDENTIFIER_KEY, $value)) {
164
            $propertyName = DataAttributesHelper::transformToValidMemberName($propertyName);
165
            $type = $value[Serializer::CLASS_IDENTIFIER_KEY];
166
            self::relationshipLinksSelf($mappings, $parent, $propertyName, $type, $data, $value);
167
            self::relationshipLinksRelated($propertyName, $mappings, $parent, $data);
168
        }
169
    }
170
171
    /**
172
     * @param \NilPortugues\Api\Mapping\Mapping[] $mappings
173
     * @param array                               $parent
174
     * @param string                              $propertyName
175
     * @param string                              $type
176
     * @param array                               $data
177
     * @param array                               $value
178
     */
179
    protected static function relationshipLinksSelf(
180
        array &$mappings,
181
        array &$parent,
182
        $propertyName,
183
        $type,
184
        array &$data,
185
        array &$value
186
    ) {
187
        if (!in_array($propertyName, RecursiveFormatterHelper::getIdProperties($mappings, $type), true)) {
188
            $data[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName] = array_merge(
189
                array_filter(
190
                    [
191
                        JsonApiTransformer::LINKS_KEY => self::setResponseDataRelationshipSelfLinks(
192
                                $propertyName,
193
                                $mappings,
194
                                $parent
195
                            ),
196
                    ]
197
                ),
198
                array_filter(
199
                    [JsonApiTransformer::DATA_KEY => PropertyHelper::setResponseDataTypeAndId($mappings, $value)]
200
                )
201
            );
202
203
            if (count($data[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName]) === 0) {
204
                unset($data[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName]);
205
            }
206
        }
207
    }
208
209
    /**
210
     * @param string                              $propertyName
211
     * @param \NilPortugues\Api\Mapping\Mapping[] $mappings
212
     * @param array                               $parent
213
     *
214
     * @return array
215
     */
216
    public static function setResponseDataRelationshipSelfLinks($propertyName, array &$mappings, array &$parent)
217
    {
218
        $data = [];
219
        $parentType = $parent[Serializer::CLASS_IDENTIFIER_KEY];
220
221
        if (\is_scalar($parentType) && !empty($mappings[$parentType])) {
222
            $copy = $parent;
223
            RecursiveFormatterHelper::formatScalarValues($copy);
224
            if (!empty($copy[Serializer::CLASS_IDENTIFIER_KEY])) {
225
                unset($copy[Serializer::CLASS_IDENTIFIER_KEY]);
226
            }
227
228
            $idProperties = array_keys($copy);
229
            foreach ($idProperties as &$property) {
230
                $property = sprintf('{%s}', $property);
231
            }
232
            $idValues = array_values($copy);
233
234
            if (!empty($mappings[$parentType]) && !empty($selfLink = $mappings[$parentType]->getRelationshipSelfUrl($propertyName))) {
235
                $url = self::buildUrl($mappings, $idProperties, $idValues, $selfLink, $parentType);
236
237
                if ($url !== $selfLink) {
238
                    $data[JsonApiTransformer::SELF_LINK][JsonApiTransformer::LINKS_HREF] = $url;
239
                }
240
            }
241
        }
242
243
        return $data;
244
    }
245
246
    /**
247
     * @param string                              $propertyName
248
     * @param \NilPortugues\Api\Mapping\Mapping[] $mappings
249
     * @param array                               $parent
250
     * @param array                               $data
251
     */
252
    protected static function relationshipLinksRelated($propertyName, array &$mappings, array &$parent, array &$data)
253
    {
254
        if (!empty($parent[Serializer::CLASS_IDENTIFIER_KEY]) && !empty($data[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName])) {
255
            $parentType = $parent[Serializer::CLASS_IDENTIFIER_KEY];
256
257
            if (\is_scalar($parentType)) {
258
                if (!empty($mappings[$parentType]) && !empty($relatedUrl = $mappings[$parentType]->getRelatedUrl($propertyName))) {
259
                    $copy = $parent;
260
                    RecursiveFormatterHelper::formatScalarValues($copy);
261
                    if (!empty($copy[Serializer::CLASS_IDENTIFIER_KEY])) {
262
                        unset($copy[Serializer::CLASS_IDENTIFIER_KEY]);
263
                    }
264
265
                    $idProperties = array_keys($copy);
266
                    foreach ($idProperties as &$property) {
267
                        $property = sprintf('{%s}', $property);
268
                    }
269
                    $idValues = array_values($copy);
270
271
                    $url = self::buildUrl($mappings, $idProperties, $idValues, $relatedUrl, $parentType);
272
273
                    if ($url !== $relatedUrl) {
274
                        $data[JsonApiTransformer::RELATIONSHIPS_KEY][$propertyName][JsonApiTransformer::LINKS_KEY][JsonApiTransformer::RELATED_LINK][JsonApiTransformer::LINKS_HREF] = $url;
275
                    }
276
                }
277
            }
278
        }
279
    }
280
281
    /**
282
     * @param \NilPortugues\Api\Mapping\Mapping[] $mappings
283
     * @param                                     $idProperties
284
     * @param                                     $idValues
285
     * @param                                     $url
286
     * @param                                     $type
287
     *
288
     * @return mixed
289
     */
290
    protected static function buildUrl(array &$mappings, $idProperties, $idValues, $url, $type)
291
    {
292
        self::removeArraysFromKeyValueReplacement($idProperties, $idValues);
293
294
        if (is_array($url) && !empty($url['name'])) {
295
            $url = $url['name'];
296
        }
297
298
        $outputUrl = \str_replace($idProperties, $idValues, $url);
299
        if ($outputUrl !== $url) {
300
            return $outputUrl;
301
        }
302
303
        $outputUrl = self::secondPassBuildUrl($mappings[$type]->getClassAlias(), $idValues, $url);
304
        if ($outputUrl !== $url) {
305
            return $outputUrl;
306
        }
307
308
        $className = $mappings[$type]->getClassName();
309
        $className = \explode('\\', $className);
310
        $className = \array_pop($className);
311
312
        $outputUrl = self::secondPassBuildUrl($className, $idValues, $url);
313
        if ($outputUrl !== $url) {
314
            return $outputUrl;
315
        }
316
317
        return $url;
318
    }
319
320
    /**
321
     * @param $idPropertyName
322
     * @param $idValues
323
     * @param $url
324
     *
325
     * @return mixed
326
     */
327
    protected static function secondPassBuildUrl($idPropertyName, $idValues, $url)
328
    {
329
        if (is_array($url) && !empty($url['name'])) {
330
            $url = $url['name'];
331
        }
332
333
        if (is_array($idValues)) {
334
            $idValues = array_shift($idValues);
335
        }
336
337
        if (!empty($idPropertyName)) {
338
            $outputUrl = self::toCamelCase($idPropertyName, $idValues, $url);
339
            if ($url !== $outputUrl) {
340
                return $outputUrl;
341
            }
342
343
            $outputUrl = self::toLowerFirstCamelCase($idPropertyName, $idValues, $url);
344
            if ($url !== $outputUrl) {
345
                return $outputUrl;
346
            }
347
348
            $outputUrl = self::toUnderScore($idPropertyName, $idValues, $url);
349
            if ($url !== $outputUrl) {
350
                return $outputUrl;
351
            }
352
        }
353
354
        return $url;
355
    }
356
357
    /**
358
     * @param $original
359
     * @param $idValues
360
     * @param $url
361
     *
362
     * @return mixed
363
     */
364
    protected static function toCamelCase($original, $idValues, $url)
365
    {
366
        $className = self::underscoreToCamelCase(self::camelCaseToUnderscore($original));
367
368
        return \str_replace('{'.$className.'}', $idValues, $url);
369
    }
370
371
    /**
372
     * @param $original
373
     * @param $idValues
374
     * @param $url
375
     *
376
     * @return mixed
377
     */
378
    protected static function toLowerFirstCamelCase($original, $idValues, $url)
379
    {
380
        $className = self::underscoreToCamelCase(self::camelCaseToUnderscore($original));
381
        $className[0] = \strtolower($className[0]);
382
383
        return \str_replace('{'.$className.'}', $idValues, $url);
384
    }
385
386
    /**
387
     * @param $original
388
     * @param $idValues
389
     * @param $url
390
     *
391
     * @return mixed
392
     */
393
    protected static function toUnderScore($original, $idValues, $url)
394
    {
395
        $className = self::camelCaseToUnderscore($original);
396
397
        return \str_replace('{'.$className.'}', $idValues, $url);
398
    }
399
400
    /**
401
     * Transforms a given string from camelCase to under_score style.
402
     *
403
     * @param string $camel
404
     * @param string $splitter
405
     *
406
     * @return string
407
     */
408
    protected static function camelCaseToUnderscore($camel, $splitter = '_')
409
    {
410
        $camel = \preg_replace(
411
            '/(?!^)[[:upper:]][[:lower:]]/',
412
            '$0',
413
            \preg_replace('/(?!^)[[:upper:]]+/', $splitter.'$0', $camel)
414
        );
415
416
        return \strtolower($camel);
417
    }
418
419
    /**
420
     * Converts a underscore string to camelCase.
421
     *
422
     * @param string $string
423
     *
424
     * @return string
425
     */
426
    protected static function underscoreToCamelCase($string)
427
    {
428
        return \str_replace(' ', '', \ucwords(\strtolower(\str_replace(['_', '-'], ' ', $string))));
429
    }
430
431
    /**
432
     * @param array $idProperties
433
     * @param array $idValues
434
     */
435
    protected static function removeArraysFromKeyValueReplacement(array &$idProperties, array &$idValues)
436
    {
437
        RecursiveDeleteHelper::deleteKeys($idValues, [Serializer::CLASS_IDENTIFIER_KEY]);
438
        RecursiveFormatterHelper::flattenObjectsWithSingleKeyScalars($idValues);
439
440
        if (is_array($idValues)) {
441
            foreach ($idValues as $key => $value) {
442
                if (is_array($value)) {
443
                    unset($idProperties[$key]);
444
                    unset($idValues[$key]);
445
                }
446
            }
447
        }
448
    }
449
}
450