Completed
Push — master ( dd341e...ba6dcb )
by Gabriel
07:12
created

MorphTo::getDictionaryKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Nip\Records\Relations;
4
5
use Exception;
6
use MongoDB\Driver\Query;
7
use Nip\Records\AbstractModels\Record;
8
use Nip\Records\Collections\Collection;
9
use Nip\Records\RecordManager;
10
use Nip\Records\Relations\Exceptions\ModelNotLoadedInRelation;
11
use Nip\Records\Relations\Traits\HasMorphTypeTrait;
12
use Nip\HelperBroker;
13
use Nip_Helper_Arrays as ArraysHelper;
14
15
/**
16
 * Class MorphToMany
17
 * @package Nip\Records\Relations
18
 */
19
class MorphTo extends BelongsTo
20
{
21
    use HasMorphTypeTrait;
22
23
    /** @noinspection PhpMissingParentCallCommonInspection
24
     * @return string
25
     * @throws ModelNotLoadedInRelation
26
     */
27 3
    public function getWithClass()
28
    {
29 3
        $type = $this->getMorphType();
30 2
        $typePlural = inflector()->pluralize($type);
31 2
        return $typePlural;
32
    }
33
34
    /**
35
     * @return mixed
36
     * @throws ModelNotLoadedInRelation
37
     */
38 3
    public function getMorphType()
39
    {
40 3
        if ($this->getItem() instanceof Record) {
41 2
            return $this->getItem()->{$this->getMorphTypeField()};
42
        }
43 1
        throw new ModelNotLoadedInRelation(
44 1
            $this->debugString()
45
        );
46
    }
47
48
    /**
49
     * @param $params
50
     * @throws Exception
51
     */
52 1
    public function addParams($params)
53
    {
54 1
        $this->checkParamMorphPrefix($params);
55 1
        parent::addParams($params);
56 1
    }
57
58
    /**
59
     * @inheritdoc
60
     */
61
    public function getEagerResults($collection)
62
    {
63
        if ($collection->count() < 1) {
64
            if ($this->getItem() instanceof Record) {
65
                return $this->getWith()->newCollection();
66
            } else {
67
                return new Collection();
68
            }
69
        }
70
        $types = $this->getTypesFromCollection($collection);
71
        $results = new Collection();
72
        foreach ($types as $type) {
0 ignored issues
show
Bug introduced by
The expression $types of type boolean|string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
73
            $manager = $this->getModelManagerInstance($type);
74
            $query = $this->getEagerQueryType($collection, $manager);
75
            $typeCollection = $manager->findByQuery($query);
76
            foreach ($typeCollection as $item) {
77
                $results->add($item);
78
            }
79
        }
80
81
        return $results;
82
    }
83
84
    /**
85
     * @param Collection $collection
86
     * @param $manager
87
     * @return Query
88
     * @throws Exception
89
     */
90 2
    public function getEagerQueryType(Collection $collection, $manager)
91
    {
92 2
        $fkList = $this->getEagerFkListType($collection, $manager);
93 2
        $query = $manager->newQuery();
94 2
        $query->where($manager->getPrimaryKey() . ' IN ?', $fkList);
95 2
        return $query;
96
    }
97
98
    /**
99
     * @param Collection $collection
100
     * @param RecordManager $manager
101
     * @return array
102
     */
103 2
    public function getEagerFkListType(Collection $collection, $manager)
104
    {
105 2
        $foreignKey = $this->getFK();
106 2
        $typeField = $this->getMorphTypeField();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $typeField is correct as $this->getMorphTypeField() (which targets Nip\Records\Relations\Tr...it::getMorphTypeField()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
107 2
        $type = $manager->getMorphName();
108 2
        $return = [];
109
110 2
        foreach ($collection as $item) {
111 2
            if ($item->{$typeField} == $type) {
112 2
                $return[] = $item->{$foreignKey};
113
            }
114
        }
115
116 2
        return array_unique($return);
117
    }
118
119
    /** @noinspection PhpMissingParentCallCommonInspection
120
     * @param Record $record
121
     * @return array
122
     * @throws \Exception
123
     */
124
    protected function getDictionaryKey(Record $record)
125
    {
126
        $key = $record->getManager()->getMorphName();
127
        $key .= '-' . $record->getPrimaryKey();
128
129
        return $key;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $key; (string) is incompatible with the return type of the parent method Nip\Records\Relations\BelongsTo::getDictionaryKey of type array.

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...
130
    }
131
132
    /**
133
     * @param $dictionary
134
     * @param $collection
135
     * @param $record
136
     * @return mixed
137
     */
138
    public function getResultsFromCollectionDictionary($dictionary, $collection, $record)
139
    {
140
        $dictionaryKey = $record->{$this->getMorphTypeField()};
141
        $dictionaryKey .= '-' . $record->{$this->getFK()};
142
        if (isset($dictionary[$dictionaryKey])) {
143
            return $dictionary[$dictionaryKey];
144
        }
145
146
        return null;
147
    }
148
149
    /**
150
     * @param Query $query
151
     * @param array $fkList
152
     * @return Query
153
     * @throws Exception
154
     */
155
    protected function populateEagerQueryFromFkList($query, $fkList)
156
    {
157
158
        return $query;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $query; (MongoDB\Driver\Query) is incompatible with the return type of the parent method Nip\Records\Relations\Re...ateEagerQueryFromFkList of type Nip\Database\Query\Select.

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...
159
    }
160
161
    /**
162
     * @param $collection
163
     * @return array
164
     */
165
    public function getTypesFromCollection($collection)
166
    {
167
        $type = $this->getMorphTypeField();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $type is correct as $this->getMorphTypeField() (which targets Nip\Records\Relations\Tr...it::getMorphTypeField()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
168
169
        /** @var ArraysHelper $arrayHelper */
170
        $arrayHelper = HelperBroker::get('Arrays');
171
        return $arrayHelper->pluck($collection, $type);
172
    }
173
}
174