Completed
Push — master ( 56c231...fd9f50 )
by
unknown
03:15
created

Driver::serializeEloquentCollection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 9
loc 9
rs 9.6667
cc 2
eloc 5
nc 2
nop 1
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 Illuminate\Contracts\Pagination\Paginator;
14
use Illuminate\Database\Eloquent\Collection;
15
use Illuminate\Database\Eloquent\Model;
16
use NilPortugues\Serializer\Drivers\Eloquent\Helper\RelationshipPropertyExtractor;
17
use NilPortugues\Serializer\Serializer;
18
use ReflectionClass;
19
20
/**
21
 * Class Driver.
22
 */
23
class Driver extends Serializer
24
{
25
    /**
26
     *
27
     */
28
    public function __construct()
29
    {
30
    }
31
32
    /**
33
     * @param mixed $value
34
     *
35
     * @return mixed|string
36
     */
37
    public function serialize($value)
38
    {
39
        $this->reset();
40
41
        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...
42
    }
43
44
    /**
45
     * Extract the data from an object.
46
     *
47
     * @param mixed $value
48
     *
49
     * @return array
50
     */
51
    protected function serializeObject($value)
52
    {
53
        if ($value instanceof Collection) {
54
            return $this->serializeEloquentCollection($value);
55
        }
56
57
        if ($value instanceof Paginator) {
58
            return $this->serializeEloquentPaginatedResource($value);
59
        }
60
61
        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...
62
            return $this->serializeEloquentModel($value);
63
        }
64
65
        return parent::serializeObject($value);
66
    }
67
68
    /**
69
     * @param Collection $value
70
     *
71
     * @return array
72
     */
73 View Code Duplication
    protected function serializeEloquentCollection(Collection $value)
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...
74
    {
75
        $items = [];
76
        foreach ($value as $v) {
77
            $items[] = $this->serializeObject($v);
78
        }
79
80
        return [self::MAP_TYPE => 'array', self::SCALAR_VALUE => $items];
81
    }
82
83
    /**
84
     * @param Paginator $value
85
     *
86
     * @return array
87
     */
88 View Code Duplication
    protected function serializeEloquentPaginatedResource(Paginator $value)
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...
89
    {
90
        $items = [];
91
        foreach ($value->items() as $v) {
92
            $items[] = $this->serializeObject($v);
93
        }
94
95
        return [self::MAP_TYPE => 'array', self::SCALAR_VALUE => $items];
96
    }
97
98
    /**
99
     * @param Model $value
100
     *
101
     * @return array
102
     */
103
    protected function serializeEloquentModel(Model $value)
104
    {
105
        $stdClass = (object) $value->attributesToArray();
106
        $data = $this->serializeData($stdClass);
107
        $data[self::CLASS_IDENTIFIER_KEY] = get_class($value);
108
109
        $methods = RelationshipPropertyExtractor::getRelationshipAsPropertyName(
110
            $value,
111
            get_class($value),
112
            new ReflectionClass($value),
113
            $this
114
        );
115
116
        if (!empty($methods)) {
117
            $data = array_merge($data, $methods);
118
        }
119
120
        return $data;
121
    }
122
}
123