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

MorphTo::getEagerResults()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 0
cts 12
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 1
crap 20
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\Relations\Exceptions\ModelNotLoadedInRelation;
10
use Nip\Records\Relations\Traits\HasMorphTypeTrait;
11
use Nip\HelperBroker;
12
use Nip_Helper_Arrays as ArraysHelper;
13
14
/**
15
 * Class MorphToMany
16
 * @package Nip\Records\Relations
17
 */
18
class MorphTo extends BelongsTo
19
{
20
    use HasMorphTypeTrait;
21
22
    /** @noinspection PhpMissingParentCallCommonInspection
23
     * @return string
24
     * @throws ModelNotLoadedInRelation
25
     */
26 3
    public function getWithClass()
27
    {
28 3
        $type = $this->getMorphType();
29 2
        $typePlural = inflector()->pluralize($type);
30 2
        return $typePlural;
31
    }
32
33
    /**
34
     * @return mixed
35
     * @throws ModelNotLoadedInRelation
36
     */
37 3
    public function getMorphType()
38
    {
39 3
        if ($this->getItem() instanceof Record) {
40 2
            return $this->getItem()->{$this->getMorphTypeField()};
41
        }
42 1
        throw new ModelNotLoadedInRelation(
43 1
            $this->debugString()
44
        );
45
    }
46
47
    /**
48
     * @param $params
49
     * @throws Exception
50
     */
51 1
    public function addParams($params)
52
    {
53 1
        $this->checkParamMorphPrefix($params);
54 1
        parent::addParams($params);
55 1
    }
56
57
    /**
58
     * @inheritdoc
59
     */
60
    public function getEagerResults($collection)
61
    {
62
        if ($collection->count() < 1) {
63
            return $this->getWith()->newCollection();
64
        }
65
        $types = $this->getTypesFromCollection($collection);
66
        $collection = new Collection();
67
        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...
68
            $manager = $this->getModelManagerInstance($type);
69
            $query = $this->getEagerQueryType($collection, $manager);
70
            $typeCollection = $manager->findByQuery($query);
71
            foreach ($typeCollection as $item) {
72
                $collection->add($item);
73
            }
74
        }
75
76
        return $collection;
77
    }
78
79
    /**
80
     * @param Collection $collection
81
     * @param $manager
82
     * @return Query
83
     * @throws Exception
84
     */
85 1
    public function getEagerQueryType(Collection $collection, $manager)
86
    {
87 1
        $fkList = $this->getEagerFkList($collection);
88 1
        $query = $manager->newQuery();
89 1
        $query->where($manager->getPrimaryKey() . ' IN ?', $fkList);
90 1
        return $query;
91
    }
92
93
    /**
94
     * @param Query $query
95
     * @param array $fkList
96
     * @return Query
97
     * @throws Exception
98
     */
99
    protected function populateEagerQueryFromFkList($query, $fkList)
100
    {
101
102
        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...
103
    }
104
105
    /**
106
     * @param $collection
107
     * @return array
108
     */
109
    public function getTypesFromCollection($collection)
110
    {
111
        $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...
112
113
        /** @var ArraysHelper $arrayHelper */
114
        $arrayHelper = HelperBroker::get('Arrays');
115
        return $arrayHelper->pluck($collection, $type);
116
    }
117
}
118