Completed
Push — master ( 9060a9...8d9a79 )
by Gabriel
02:31 queued 11s
created

SearchableRecordsTrait::findLast()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Nip\Records\Traits\Searchable;
4
5
use Nip\Database\Query\AbstractQuery as Query;
6
use Nip\Records\Navigator\Pagination\Paginator;
7
use Nip\Records\AbstractModels\Record;
8
use Nip\Records\Collections\Collection as RecordCollection;
9
10
/**
11
 * Trait SearchableRecordsTrait
12
 * @package Nip\Records\Traits\Searchable
13
 */
14
trait SearchableRecordsTrait
15
{
16
17
    /**
18
     * Returns paginated results
19
     * @param Paginator $paginator
20
     * @param array $params
21
     * @return mixed
22
     */
23
    public function paginate(Paginator $paginator, $params = [])
24
    {
25
        $query = $this->paramsToQuery($params);
0 ignored issues
show
Bug introduced by
It seems like paramsToQuery() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

25
        /** @scrutinizer ignore-call */ 
26
        $query = $this->paramsToQuery($params);
Loading history...
26
27
        $countQuery = $this->getDB()->newSelect();
0 ignored issues
show
Bug introduced by
It seems like getDB() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

27
        $countQuery = $this->/** @scrutinizer ignore-call */ getDB()->newSelect();
Loading history...
28
        $countQuery->count(['*', 'count']);
29
        $countQuery->from([$query, 'tbl']);
30
        $results = $countQuery->execute()->fetchResults();
31
        $count = $results[0]['count'];
32
33
        $paginator->setCount($count);
0 ignored issues
show
Bug introduced by
The method setCount() does not exist on Nip\Records\Navigator\Pagination\Paginator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

33
        $paginator->/** @scrutinizer ignore-call */ 
34
                    setCount($count);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
34
35
        $params['limit'] = $paginator->getLimits();
0 ignored issues
show
Bug introduced by
The method getLimits() does not exist on Nip\Records\Navigator\Pagination\Paginator. Did you maybe mean getLimitStart()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

35
        /** @scrutinizer ignore-call */ 
36
        $params['limit'] = $paginator->getLimits();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
36
37
        return $this->findByParams($params);
38
    }
39
40
    /**
41
     * @param array $params
42
     */
43 3
    protected function injectParams(&$params = [])
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

43
    protected function injectParams(/** @scrutinizer ignore-unused */ &$params = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
44
    {
45 3
    }
46
47
    /**
48
     * @return RecordCollection
49
     */
50
    public function findAll()
51
    {
52
        return $this->findByParams();
53
    }
54
55
    /**
56
     * @param int $count
57
     * @return RecordCollection
58
     */
59
    public function findLast($count = 9)
60
    {
61
        return $this->findByParams([
62
            'limit' => $count,
63
        ]);
64
    }
65
66
    /**
67
     * Checks the registry before fetching from the database
68
     * @param mixed $primary
69
     * @return Record
70
     */
71
    public function findOne($primary)
72
    {
73
        $item = $this->getRegistry()->get($primary);
0 ignored issues
show
Bug introduced by
It seems like getRegistry() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

73
        $item = $this->/** @scrutinizer ignore-call */ getRegistry()->get($primary);
Loading history...
74
        if (!$item) {
75
            $all = $this->getRegistry()->get("all");
76
            if ($all) {
77
                $item = $all[$primary];
78
            }
79
            if (!$item) {
80
                $params['where'][] = ["`{$this->getTable()}`.`{$this->getPrimaryKey()}` = ?", $primary];
0 ignored issues
show
Bug introduced by
It seems like getTable() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

80
                $params['where'][] = ["`{$this->/** @scrutinizer ignore-call */ getTable()}`.`{$this->getPrimaryKey()}` = ?", $primary];
Loading history...
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
Bug introduced by
It seems like getPrimaryKey() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

80
                $params['where'][] = ["`{$this->getTable()}`.`{$this->/** @scrutinizer ignore-call */ getPrimaryKey()}` = ?", $primary];
Loading history...
81
                $item = $this->findOneByParams($params);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $item is correct as $this->findOneByParams($params) targeting Nip\Records\Traits\Searc...rait::findOneByParams() 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...
82
                if ($item) {
0 ignored issues
show
introduced by
$item is of type null, thus it always evaluated to false.
Loading history...
83
                    $this->getRegistry()->set($primary, $item);
84
                }
85
86
                return $item;
87
            }
88
        }
89
90
        return $item;
91
    }
92
93
    /**
94
     * When searching by primary key, look for items in current registry before
95
     * fetching them from the database
96
     *
97
     * @param array $pk_list
98
     * @return RecordCollection
99
     */
100
    public function findByPrimary($pk_list = [])
101
    {
102
        $pk = $this->getPrimaryKey();
103
        $return = $this->newCollection();
0 ignored issues
show
Bug introduced by
It seems like newCollection() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

103
        /** @scrutinizer ignore-call */ 
104
        $return = $this->newCollection();
Loading history...
104
105
        if ($pk_list) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pk_list of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
106
            $pk_list = array_unique($pk_list);
107
            foreach ($pk_list as $key => $value) {
108
                $item = $this->getRegistry()->get($value);
109
                if ($item) {
110
                    unset($pk_list[$key]);
111
                    $return[$item->{$pk}] = $item;
112
                }
113
            }
114
            if ($pk_list) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pk_list of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
115
                $query = $this->paramsToQuery();
116
                $query->where("$pk IN ?", $pk_list);
117
                $items = $this->findByQuery($query);
118
119
                if (count($items)) {
120
                    foreach ($items as $item) {
121
                        $this->getRegistry()->set($item->{$pk}, $item);
122
                        $return[$item->{$pk}] = $item;
123
                    }
124
                }
125
            }
126
        }
127
128
        return $return;
129
    }
130
131
132
    /**
133
     * Finds one Record using params array
134
     *
135
     * @param array $params
136
     * @return Record|null
137
     */
138
    public function findOneByParams(array $params = [])
139
    {
140
        $params['limit'] = 1;
141
        $records = $this->findByParams($params);
142
        if (count($records) > 0) {
143
            return $records->rewind();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $records->rewind() targeting Nip\Collections\AbstractCollection::rewind() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

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

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

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

Loading history...
Bug Best Practice introduced by
The expression return $records->rewind() returns the type void which is incompatible with the documented return type Nip\Records\AbstractModels\Record|null.
Loading history...
144
        }
145
146
        return null;
147
    }
148
149
    /**
150
     * Finds Records using params array
151
     *
152
     * @param array $params
153
     * @return RecordCollection
154
     */
155
    public function findByParams($params = [])
156
    {
157
        $query = $this->paramsToQuery($params);
158
159
        return $this->findByQuery($query, $params);
160
    }
161
162
    /**
163
     * @param Query $query
164
     * @param array $params
165
     * @return bool
166
     */
167
    public function findOneByQuery($query, $params = [])
168
    {
169
        $query->limit(1);
170
        $return = $this->findByQuery($query, $params);
171
        if (count($return) > 0) {
172
            return $return->rewind();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $return->rewind() returns the type void which is incompatible with the documented return type boolean.
Loading history...
Bug introduced by
Are you sure the usage of $return->rewind() targeting Nip\Collections\AbstractCollection::rewind() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

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

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

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

Loading history...
173
        }
174
175
        return null;
176
    }
177
178
    /**
179
     * @param $field
180
     * @param $value
181
     * @return mixed
182
     */
183
    public function findByField($field, $value)
184
    {
185
        $params['where'][] = ["$field " . (is_array($value) ? "IN" : "=") . " ?", $value];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
186
187
        return $this->findByParams($params);
188
    }
189
190
    /**
191
     * @param Query $query
192
     * @param array $params
193
     * @return RecordCollection
194
     */
195
    public function findByQuery($query, $params = [])
196
    {
197
        $return = $this->newCollection();
198
199
        $results = $this->getDB()->execute($query);
200
        if ($results->numRows() > 0) {
201
            $pk = $this->getPrimaryKey();
202
            /** @noinspection PhpAssignmentInConditionInspection */
203
            while ($row = $results->fetchResult()) {
204
                $item = $this->getNew($row);
0 ignored issues
show
Bug introduced by
It seems like getNew() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

204
                /** @scrutinizer ignore-call */ 
205
                $item = $this->getNew($row);
Loading history...
205
                if (is_string($pk)) {
206
                    $this->getRegistry()->set($item->getPrimaryKey(), $item);
207
                }
208
                if (isset($params['indexKey']) && !empty($params['indexKey'])) {
209
                    $return->add($item, $params['indexKey']);
210
                } else {
211
                    $return->add($item);
212
                }
213
            }
214
        }
215
216
        return $return;
217
    }
218
}
219