JSendSerializer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/**
4
 * Author: Nil Portugués Calderó <[email protected]>
5
 * Date: 8/16/15
6
 * Time: 4:43 AM.
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\Laravel5\JSendSerializer;
12
13
use ErrorException;
14
use Illuminate\Database\Eloquent\Model;
15
use NilPortugues\Api\JSend\JSendTransformer;
16
use NilPortugues\Serializer\DeepCopySerializer;
17
use ReflectionClass;
18
use ReflectionMethod;
19
20
/**
21
 * Class JSendSerializer.
22
 */
23
class JSendSerializer extends DeepCopySerializer
24
{
25
    /**
26
     * @param JSendTransformer $jSendTransformer
27
     */
28
    public function __construct(JSendTransformer $jSendTransformer)
0 ignored issues
show
Unused Code Comprehensibility introduced by
Overwriting this method does not seem to be necessary. You may want to remove this method.
Loading history...
29
    {
30
        parent::__construct($jSendTransformer);
31
    }
32
33
    /**
34
     * Extract the data from an object.
35
     *
36
     * @param mixed $value
37
     *
38
     * @return array
39
     */
40
    protected function serializeObject($value)
41
    {
42 View Code Duplication
        if ($value instanceof \Illuminate\Database\Eloquent\Collection) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
43
            $items = [];
44
            foreach ($value as &$v) {
45
                $items[] = $this->serializeObject($v);
46
            }
47
48
            return [self::MAP_TYPE => 'array', self::SCALAR_VALUE => $items];
49
        }
50
51 View Code Duplication
        if ($value instanceof \Illuminate\Contracts\Pagination\Paginator) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
52
            $items = [];
53
            foreach ($value->items() as &$v) {
0 ignored issues
show
Bug introduced by
The expression $value->items() cannot be used as a reference.

Let?s assume that you have the following foreach statement:

foreach ($array as &$itemValue) { }

$itemValue is assigned by reference. This is possible because the expression (in the example $array) can be used as a reference target.

However, if we were to replace $array with something different like the result of a function call as in

foreach (getArray() as &$itemValue) { }

then assigning by reference is not possible anymore as there is no target that could be modified.

Available Fixes

1. Do not assign by reference
foreach (getArray() as $itemValue) { }
2. Assign to a local variable first
$array = getArray();
foreach ($array as &$itemValue) {}
3. Return a reference
function &getArray() { $array = array(); return $array; }

foreach (getArray() as &$itemValue) { }
Loading history...
54
                $items[] = $this->serializeObject($v);
55
            }
56
57
            return [self::MAP_TYPE => 'array', self::SCALAR_VALUE => $items];
58
        }
59
        
60
        if (is_subclass_of($value, Model::class, true)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Illuminate\Database\Eloquent\Model::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
61
62
            $stdClass = (object) $value->getAttributes();
63
            $data =  $this->serializeData($stdClass);
64
            $data[self::CLASS_IDENTIFIER_KEY] = get_class($value);
65
66
            $methods = $this->getRelationshipMethodsAsPropertyName($value, get_class($value), new ReflectionClass($value));
67
68
            if (!empty($methods)) {
69
                $data = array_merge($data, $methods);
70
            }
71
72
            return $data;
73
        }
74
75
        return parent::serializeObject($value);
76
    }
77
78
    /**
79
     * @param                 $value
80
     * @param string          $className
81
     * @param ReflectionClass $reflection
82
     *
83
     * @return array
84
     */
85
    protected function getRelationshipMethodsAsPropertyName($value, $className, ReflectionClass $reflection)
86
    {
87
88
        $methods = [];
89
        foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
90
            if (ltrim($method->class, "\\") === ltrim($className, "\\")) {
91
92
                $name = $method->name;
93
                $reflectionMethod = $reflection->getMethod($name);
94
95
                // Eloquent relations do not include parameters, so we'll be filtering based on this criteria.
96
                if (0 == $reflectionMethod->getNumberOfParameters()) {
97
                    try {
98
                        $returned = $reflectionMethod->invoke($value);
99
                        //All operations (eg: boolean operations) are now filtered out.
100
                        if (is_object($returned)) {
101
102
                            // Only keep those methods as properties if these are returning Eloquent relations.
103
                            // But do not run the operation as it is an expensive operation.
104
                            if (false !== strpos(get_class($returned), 'Illuminate\Database\Eloquent\Relations')) {
105
106
                                $items = [];
107
                                foreach ($returned->getResults() as $model) {
108
109
                                    if (is_object($model)) {
110
                                        $stdClass = (object) $model->getAttributes();
111
                                        $data =  $this->serializeData($stdClass);
112
                                        $data[self::CLASS_IDENTIFIER_KEY] = get_class($model);
113
114
                                        $items[] = $data;
115
                                    }
116
                                }
117
                                if (!empty($items)) {
118
                                    $methods[$name] = [self::MAP_TYPE => 'array', self::SCALAR_VALUE => $items];
119
                                }
120
121
                            }
122
                        }
123
                    } catch (ErrorException $e) {}
0 ignored issues
show
Unused Code introduced by
This catchblock is empty and will swallow any caught exception.

This check looks for ``catch` blocks that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

Empty catch blocks will swallow any caught exception, sometimes causing bugs in your code that are very hard to debug. Consider logging the exception to a debug log or re-throwing it in some way, shape or form.

Loading history...
124
                }
125
            }
126
        }
127
128
        return $methods;
129
    }
130
}
131