Driver::serializeEloquentCollection()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Importance

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