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

HasOneOrMany::getEagerQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 7
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 7
loc 7
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Nip\Records\Relations;
4
5
use Nip\Database\Query\Select as Query;
6
use Nip\HelperBroker;
7
use Nip\Records\AbstractModels\Record as Record;
8
use Nip\Records\Collections\Associated as AssociatedCollection;
9
use Nip\Records\Collections\Collection;
10
use Nip\Records\Collections\Collection as RecordCollection;
11
use Nip\Records\Relations\Traits\HasCollectionResults;
12
13
/**
14
 * Class HasOneOrMany
15
 * @package Nip\Records\Relations
16
 */
17
abstract class HasOneOrMany extends Relation
18
{
19
    use HasCollectionResults;
20
21
    /**
22
     * @var string
23
     */
24
    protected $type = 'hasMany';
25
26
    /**
27
     * @return bool
28
     */
29
    public function save()
30
    {
31
        if ($this->hasResults()) {
32
            $collection = $this->getResults();
33
            foreach ($collection as $item) {
0 ignored issues
show
Bug introduced by
The expression $collection of type object<Nip\Records\Colle...ect<Nip\Records\Record> 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...
34
                $this->saveResult($item);
35
            }
36
        }
37
        return true;
38
    }
39
40
    /**
41
     * @return bool
42
     */
43
    public function hasResults()
44
    {
45
        return $this->isPopulated() && count($this->getResults()) > 0;
46
    }
47
48
    /**
49
     * @param Record $item
50
     */
51 1
    public function saveResult(Record $item)
52
    {
53 1
        $pk = $this->getManager()->getPrimaryKey();
54 1
        $fk = $this->getFK();
55 1
        $item->{$fk} = $this->getItem()->{$pk};
56 1
        $item->saveRecord();
57 1
    }
58
59
    public function initResults()
60
    {
61
        $query = $this->getQuery();
62
        $items = $this->getWith()->findByQuery($query);
63
        $collection = $this->newCollection();
64
        $this->populateCollection($collection, $items);
65
        $this->setResults($collection);
66
    }
67
68
    /**
69
     * @param RecordCollection $collection
70
     * @param Collection $items
71
     */
72
    public function populateCollection(RecordCollection $collection, $items)
73
    {
74
        foreach ($items as $item) {
75
            $collection->add($item);
76
        }
77
    }
78
79
    /** @noinspection PhpMissingParentCallCommonInspection
80
     * @inheritdoc
81
     */
82 1
    public function populateEagerQueryFromFkList($query, $fkList)
83
    {
84 1
        $query->where($this->getFK() . ' IN ?', $fkList);
85 1
        return $query;
86
    }
87
88
    /** @noinspection PhpMissingParentCallCommonInspection
89
     * @param RecordCollection $collection
90
     * @return array
91
     */
92 1
    public function getEagerFkList(RecordCollection $collection)
93
    {
94 1
        if ($collection->isEmpty()) {
95 1
            return [];
96
        }
97 1
        $key = $collection->getManager()->getPrimaryKey();
98 1
        $return = HelperBroker::get('Arrays')->pluck($collection, $key);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Nip\Helpers\AbstractHelper as the method pluck() does only exist in the following sub-classes of Nip\Helpers\AbstractHelper: Nip_Helper_Arrays. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
99
100 1
        return array_unique($return);
101
    }
102
103
    /**
104
     * @param array $dictionary
105
     * @param Collection $collection
106
     * @param Record $record
107
     * @return AssociatedCollection
108
     */
109
    public function getResultsFromCollectionDictionary($dictionary, $collection, $record)
110
    {
111
        $fk = $record->getManager()->getPrimaryKey();
112
        $pk = $record->{$fk};
113
        $collection = $this->newCollection();
114
115
        if ($dictionary[$pk]) {
116
            foreach ($dictionary[$pk] as $record) {
117
                $collection->add($record);
118
            }
119
        }
120
        return $collection;
121
    }
122
123
    /**
124
     * Build model dictionary keyed by the relation's foreign key.
125
     *
126
     * @param RecordCollection $collection
127
     * @return array
128
     */
129
    protected function buildDictionary(RecordCollection $collection)
130
    {
131
        $dictionary = [];
132
        $pk = $this->getDictionaryKey();
133
        foreach ($collection as $record) {
134
            $dictionary[$record->{$pk}][] = $record;
135
        }
136
        return $dictionary;
137
    }
138
139
    /**
140
     * @return string
141
     */
142
    protected function getDictionaryKey()
143
    {
144
        return $this->getFK();
145
    }
146
}
147