Completed
Push — master ( 63c2be...192105 )
by
unknown
04:47
created

Driver::getRelationshipAsPropertyName()   C

Complexity

Conditions 11
Paths 31

Size

Total Lines 46
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 46
rs 5.2653
cc 11
eloc 23
nc 31
nop 3

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Author: Nil Portugués Calderó <[email protected]>
4
 * Date: 11/21/15
5
 * Time: 3:44 PM
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace NilPortugues\Serializer\Drivers\Eloquent;
12
13
use NilPortugues\Serializer\Serializer;
14
use ErrorException;
15
use Illuminate\Database\Eloquent\Model;
16
use ReflectionClass;
17
use ReflectionMethod;
18
19
/**
20
 * Class Driver
21
 * @package NilPortugues\Laravel5\Serializer
22
 */
23
class Driver extends Serializer
24
{
25
    /**
26
     * @var array
27
     */
28
    private $forbiddenFunction = [
29
        'forceDelete',
30
        'forceFill',
31
        'delete',
32
        'newQueryWithoutScopes',
33
        'newQuery',
34
        'bootIfNotBooted',
35
        'boot',
36
        'bootTraits',
37
        'clearBootedModels',
38
        'query',
39
        'onWriteConnection',
40
        'delete',
41
        'forceDelete',
42
        'performDeleteOnModel',
43
        'flushEventListeners',
44
        'push',
45
        'touchOwners',
46
        'touch',
47
        'updateTimestamps',
48
        'freshTimestamp',
49
        'freshTimestampString',
50
        'newQuery',
51
        'newQueryWithoutScopes',
52
        'newBaseQueryBuilder',
53
        'usesTimestamps',
54
        'reguard',
55
        'isUnguarded',
56
        'totallyGuarded',
57
        'syncOriginal',
58
        'getConnectionResolver',
59
        'unsetConnectionResolver',
60
        'getEventDispatcher',
61
        'unsetEventDispatcher',
62
        '__toString',
63
        '__wakeup',
64
    ];
65
    /**
66
     *
67
     */
68
    public function __construct()
69
    {
70
71
    }
72
73
    /**
74
     * @param mixed $value
75
     *
76
     * @return mixed|string
77
     */
78
    public function serialize($value)
79
    {
80
        $this->reset();
81
        return $this->serializeObject($value);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->serializeObject($value); (array) is incompatible with the return type of the parent method NilPortugues\Serializer\Serializer::serialize of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
82
    }
83
84
    /**
85
     * Extract the data from an object.
86
     *
87
     * @param mixed $value
88
     *
89
     * @return array
90
     */
91
    protected function serializeObject($value)
92
    {
93 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...
94
            $items = [];
95
            foreach ($value as $v) {
96
                $items[] = $this->serializeObject($v);
97
            }
98
99
            return [self::MAP_TYPE => 'array', self::SCALAR_VALUE => $items];
100
        }
101
102 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...
103
            $items = [];
104
            foreach ($value->items() as $v) {
105
                $items[] = $this->serializeObject($v);
106
            }
107
108
            return [self::MAP_TYPE => 'array', self::SCALAR_VALUE => $items];
109
        }
110
111
        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...
112
            $stdClass = (object) $value->attributesToArray();
113
            $data = $this->serializeData($stdClass);
114
            $data[self::CLASS_IDENTIFIER_KEY] = \get_class($value);
115
116
            $methods = $this->getRelationshipAsPropertyName($value, get_class($value), new ReflectionClass($value));
117
118
            if (!empty($methods)) {
119
                $data = \array_merge($data, $methods);
120
            }
121
122
            return $data;
123
        }
124
125
        return parent::serializeObject($value);
126
    }
127
128
    /**
129
     * @param                 $value
130
     * @param string          $className
131
     * @param ReflectionClass $reflection
132
     *
133
     * @return array
134
     */
135
    protected function getRelationshipAsPropertyName($value, $className, ReflectionClass $reflection)
136
    {
137
        $methods = [];
138
        foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
139
            if (\ltrim($method->class, '\\') === \ltrim($className, '\\')) {
140
                $name = $method->name;
141
                $reflectionMethod = $reflection->getMethod($name);
142
143
                // Eloquent relations do not include parameters, so we'll be filtering based on this criteria.
144
                if (0 == $reflectionMethod->getNumberOfParameters()) {
145
                    try {
146
147
                        if (false === in_array($value, $this->forbiddenFunction, true)) {
148
                            $returned = $reflectionMethod->invoke($value);
149
                            //All operations (eg: boolean operations) are now filtered out.
150
                            if (\is_object($returned)) {
151
152
                                // Only keep those methods as properties if these are returning Eloquent relations.
153
                                // But do not run the operation as it is an expensive operation.
154
                                if (false !== \strpos(\get_class($returned), 'Illuminate\Database\Eloquent\Relations')) {
155
                                    $items = [];
156
                                    foreach ($returned->getResults() as $model) {
157
                                        if (\is_object($model)) {
158
                                            /** @var Model $model */
159
                                            $stdClass = (object) $model->getAttributes();
160
                                            $data = $this->serializeData($stdClass);
161
                                            $data[self::CLASS_IDENTIFIER_KEY] = \get_class($model);
162
163
                                            $items[] = $data;
164
                                        }
165
                                    }
166
                                    if (!empty($items)) {
167
                                        $methods[$name] = [self::MAP_TYPE => 'array', self::SCALAR_VALUE => $items];
168
                                    }
169
                                }
170
                            }
171
                        }
172
173
                    } catch (ErrorException $e) {
174
                    }
175
                }
176
            }
177
        }
178
179
        return $methods;
180
    }
181
} 
182