GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

ActiveRecordsTrait::countByQuery()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 1
dl 0
loc 14
ccs 0
cts 8
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Nip\Records\Traits\ActiveRecord;
4
5
use Nip\Database\Connections\Connection;
6
use Nip\Database\Query\AbstractQuery as Query;
7
use Nip\Database\Query\Delete as DeleteQuery;
8
use Nip\Database\Query\Insert as InsertQuery;
9
use Nip\Database\Query\Select as SelectQuery;
10
use Nip\Database\Query\Update as UpdateQuery;
11
use Nip\Database\Result;
12
use Nip\Paginator;
13
use Nip\Records\AbstractModels\Record;
14
use Nip\Records\Collections\Collection as RecordCollection;
15
16
/**
17
 * Class ActiveRecordsTrait
18
 * @package Nip\Records\Traits\ActiveRecord
19
 */
20
trait ActiveRecordsTrait
21
{
22
23
    /**
24
     * @var Connection
25
     */
26
    protected $connection = null;
27
28
    /**
29
     * @var null|string
30
     */
31
    protected $table = null;
32
33
    protected $tableStructure = null;
34
35
    /**
36
     * @var null|string
37
     */
38
    protected $primaryKey = null;
39
    protected $fields = null;
40
    protected $uniqueFields = null;
41
42
    /**
43
     * @var null|string
44
     */
45
    protected $foreignKey = null;
46
47
    /**
48
     * @return SelectQuery
49
     */
50
    public function newSelectQuery()
51
    {
52
        return $this->newQuery('select');
53
    }
54
55
    /**
56
     * Factory
57
     * @param string $type
58
     * @return Query|SelectQuery|InsertQuery|DeleteQuery|UpdateQuery
59
     */
60
    public function newQuery($type = 'select')
61
    {
62
        $query = $this->getDB()->newQuery($type);
63
        $query->cols("`" . $this->getTable() . "`.*");
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::cols() has too many arguments starting with '`' . $this->getTable() . '`.*'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
64
        $query->from($this->getFullNameTable());
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::from() has too many arguments starting with $this->getFullNameTable().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
65
        $query->table($this->getTable());
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::table() has too many arguments starting with $this->getTable().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
66
67
        return $query;
68
    }
69
70
    /**
71
     * @return Connection
72
     */
73 2
    public function getDB()
74
    {
75 2
        if ($this->connection == null) {
76 1
            $this->initDB();
77
        }
78
79 2
        $this->checkDB();
80
81 2
        return $this->connection;
82
    }
83
84 1
    protected function initDB()
85
    {
86 1
        $this->setDB($this->newDbConnection());
87 1
    }
88
89
    /**
90
     * @param Connection $connection
91
     * @return $this
92
     */
93 21
    public function setDB($connection)
94
    {
95 21
        $this->connection = $connection;
96
97 21
        return $this;
98
    }
99
100
    /**
101
     * @return Connection
102
     */
103 1
    protected function newDbConnection()
104
    {
105 1
        return app('db.connection');
106
    }
107
108 2
    public function checkDB()
109
    {
110 2
        if (!$this->hasDB()) {
111
            trigger_error("Database connection missing for [" . get_class($this) . "]", E_USER_ERROR);
112
        }
113 2
    }
114
115
    /**
116
     * @return bool
117
     */
118 2
    public function hasDB()
119
    {
120 2
        return $this->connection instanceof Connection;
121
    }
122
123
    /**
124
     * @return string
125
     */
126 2
    public function getTable()
127
    {
128 2
        if ($this->table === null) {
129 1
            $this->initTable();
130
        }
131
132 2
        return $this->table;
133
    }
134
135
    /**
136
     * @param null $table
137
     */
138 21
    public function setTable($table)
139
    {
140 21
        $this->table = $table;
141 21
    }
142
143 1
    protected function initTable()
144
    {
145 1
        $this->setTable($this->generateTable());
146 1
    }
147
148
    /**
149
     * @return string
150
     */
151 1
    protected function generateTable()
152
    {
153 1
        return str_replace('-', '_', $this->getController());
0 ignored issues
show
Bug introduced by
It seems like getController() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
154
    }
155
156
    /**
157
     * @return string
158
     */
159 2
    public function getFullNameTable()
160
    {
161 2
        $database = $this->getDB()->getDatabase();
162
163 2
        return $database ? $database . '.' . $this->getTable() : $this->getTable();
164
    }
165
166
    /**
167
     * @return null
168
     */
169
    public function getFields()
170
    {
171
        if ($this->fields === null) {
172
            $this->initFields();
173
        }
174
175
        return $this->fields;
176
    }
177
178
    public function initFields()
179
    {
180
        $structure = $this->getTableStructure();
181
        $this->fields = array_keys($structure['fields']);
182
    }
183
184
    /**
185
     * @return mixed
186
     */
187
    protected function getTableStructure()
188
    {
189
        if ($this->tableStructure == null) {
190
            $this->initTableStructure();
191
        }
192
193
        return $this->tableStructure;
194
    }
195
196
    /**
197
     * @param null $tableStructure
198
     */
199 1
    public function setTableStructure($tableStructure)
200
    {
201 1
        $this->tableStructure = $tableStructure;
202 1
    }
203
204
    protected function initTableStructure()
205
    {
206
        $this->setTableStructure($this->getDB()->getMetadata()->describeTable($this->getTable()));
207
    }
208
209
    /**
210
     * @return InsertQuery
211
     */
212
    public function newInsertQuery()
213
    {
214
        return $this->newQuery('insert');
215
    }
216
217
    /**
218
     * Updates a Record's database entry
219
     * @param Record $model
220
     * @return bool|Result
221
     */
222
    public function update(Record $model)
223
    {
224
        $query = $this->updateQuery($model);
225
226
        if ($query) {
227
            return $query->execute();
228
        }
229
230
        return false;
231
    }
232
233
    /**
234
     * @param Record $model
235
     * @return bool|UpdateQuery
236
     */
237
    public function updateQuery(Record $model)
238
    {
239
        $pk = $this->getPrimaryKey();
240
        if (!is_array($pk)) {
241
            $pk = [$pk];
242
        }
243
244
        $data = $this->getQueryModelData($model);
0 ignored issues
show
Bug introduced by
It seems like getQueryModelData() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
245
246
        if ($data) {
247
            $query = $this->newUpdateQuery();
248
            $query->data($data);
0 ignored issues
show
Unused Code introduced by
The call to Update::data() has too many arguments starting with $data.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
249
250
            foreach ($pk as $key) {
251
                $query->where("$key = ?", $model->{$key});
252
            }
253
254
            return $query;
255
        }
256
257
        return false;
258
    }
259
260
    /**
261
     * @return string
262
     */
263 7
    public function getPrimaryKey()
264
    {
265 7
        if ($this->primaryKey === null) {
266
            $this->initPrimaryKey();
267
        }
268
269 7
        return $this->primaryKey;
270
    }
271
272
    /**
273
     * @param null|string $primaryKey
274
     */
275 7
    public function setPrimaryKey($primaryKey)
276
    {
277 7
        $this->primaryKey = $primaryKey;
278 7
    }
279
280
    protected function initPrimaryKey()
281
    {
282
        $this->setPrimaryKey($this->generatePrimaryKey());
283
    }
284
285
    /**
286
     * @return string
287
     */
288
    public function generatePrimaryKey()
289
    {
290
        $structure = $this->getTableStructure();
291
        $primaryKey = false;
292
        if (is_array($structure) && isset($structure['indexes']['PRIMARY']['fields'])) {
293
            $primaryKey = $structure['indexes']['PRIMARY']['fields'];
294
            if (count($primaryKey) == 1) {
295
                $primaryKey = reset($primaryKey);
296
            }
297
        }
298
299
        return $primaryKey;
300
    }
301
302
    /**
303
     * @return UpdateQuery
304
     */
305
    public function newUpdateQuery()
306
    {
307
        return $this->newQuery('update');
308
    }
309
310
    /**
311
     * Saves a Record's database entry
312
     * @param Record $model
313
     * @return mixed
314
     */
315
    public function save(Record $model)
316
    {
317
        $pk = $this->getPrimaryKey();
318
319
        if (isset($model->{$pk})) {
320
            $model->update();
321
322
            return $model->{$pk};
323
        } else {
324
            /** @var Record $previous */
325
            $previous = $model->exists();
326
327
            if ($previous) {
328
                $data = $model->toArray();
329
330
                if ($data) {
331
                    $previous->writeData($model->toArray());
332
                }
333
                $previous->update();
334
335
                $model->writeData($previous->toArray());
336
337
                return $model->getPrimaryKey();
338
            }
339
        }
340
341
        $model->insert();
342
343
        return $model->getPrimaryKey();
344
    }
345
346
    /**
347
     * Delete a Record's database entry
348
     *
349
     * @param mixed|Record $input
350
     */
351
    public function delete($input)
352
    {
353
        $pk = $this->getPrimaryKey();
354
355
        if ($input instanceof $this->model) {
0 ignored issues
show
Bug introduced by
The property model does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
356
            $primary = $input->getPrimaryKey();
357
        } else {
358
            $primary = $input;
359
        }
360
361
        $query = $this->newDeleteQuery();
362
        $query->where("$pk = ?", $primary);
363
        $query->limit(1);
364
365
        $this->getDB()->execute($query);
366
    }
367
368
    /**
369
     * @return DeleteQuery
370
     */
371
    public function newDeleteQuery()
372
    {
373
        return $this->newQuery('delete');
374
    }
375
376
    /**
377
     * Delete a Record's database entry
378
     * @param array $params
379
     * @return $this
380
     */
381
    public function deleteByParams($params = [])
382
    {
383
        extract($params);
384
385
        $query = $this->newDeleteQuery();
386
387
        if (isset($where)) {
388
            if (is_array($where)) {
389
                foreach ($where as $condition) {
390
                    $condition = (array)$condition;
391
                    $query->where($condition[0], $condition[1]);
392
                }
393
            } else {
394
                call_user_func_array([$query, 'where'], $where);
395
            }
396
        }
397
398
        if (isset($order)) {
399
            call_user_func_array([$query, 'order'], $order);
400
        }
401
402
        if (isset($limit)) {
403
            call_user_func_array([$query, 'limit'], $limit);
404
        }
405
406
        $this->getDB()->execute($query);
407
408
        return $this;
409
    }
410
411
    /**
412
     * Returns paginated results
413
     * @param Paginator $paginator
414
     * @param array $params
415
     * @return mixed
416
     */
417
    public function paginate(Paginator $paginator, $params = [])
418
    {
419
        $query = $this->paramsToQuery($params);
420
421
        $countQuery = $this->getDB()->newSelect();
422
        $countQuery->count(['*', 'count']);
0 ignored issues
show
Unused Code introduced by
The call to Select::count() has too many arguments starting with array('*', 'count').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
423
        $countQuery->from([$query, 'tbl']);
0 ignored issues
show
Unused Code introduced by
The call to Select::from() has too many arguments starting with array($query, 'tbl').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
424
        $results = $countQuery->execute()->fetchResults();
425
        $count = $results[0]['count'];
426
427
        $paginator->setCount($count);
428
429
        $params['limit'] = $paginator->getLimits();
430
431
        return $this->findByParams($params);
0 ignored issues
show
Bug introduced by
It seems like findByParams() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
432
    }
433
434
    /**
435
     * @param array $params
436
     * @return SelectQuery
437
     */
438
    public function paramsToQuery($params = [])
439
    {
440
        $this->injectParams($params);
441
442
        $query = $this->newQuery('select');
443
        $query->addParams($params);
444
445
        return $query;
446
    }
447
448
    /**
449
     * @param array $params
450
     */
451
    protected function injectParams(&$params = [])
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed.

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

Loading history...
452
    {
453
    }
454
455
    /**
456
     * Checks the registry before fetching from the database
457
     * @param mixed $primary
458
     * @return Record
459
     */
460
    public function findOne($primary)
461
    {
462
        $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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
463
        if (!$item) {
464
            $all = $this->getRegistry()->get("all");
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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
465
            if ($all) {
466
                $item = $all[$primary];
467
            }
468
            if (!$item) {
469
                $params['where'][] = ["`{$this->getTable()}`.`{$this->getPrimaryKey()}` = ?", $primary];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
470
                $item = $this->findOneByParams($params);
0 ignored issues
show
Bug introduced by
The method findOneByParams() does not exist on Nip\Records\Traits\ActiveRecord\ActiveRecordsTrait. Did you maybe mean findOne()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
471
                if ($item) {
472
                    $this->getRegistry()->set($primary, $item);
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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
473
                }
474
475
                return $item;
476
            }
477
        }
478
479
        return $item;
480
    }
481
482
    /**
483
     * @param Query $query
484
     * @param array $params
485
     * @return bool
486
     */
487
    public function findOneByQuery($query, $params = [])
488
    {
489
        $query->limit(1);
490
        $return = $this->findByQuery($query, $params);
491
        if (count($return) > 0) {
492
            return $return->rewind();
493
        }
494
495
        return false;
496
    }
497
498
    /**
499
     * @param $query
500
     * @param array $params
501
     * @return RecordCollection
502
     */
503
    public function findByQuery($query, $params = [])
504
    {
505
        $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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
506
507
        $results = $this->getDB()->execute($query);
508
        if ($results->numRows() > 0) {
509
            $pk = $this->getPrimaryKey();
510
            /** @noinspection PhpAssignmentInConditionInspection */
511
            while ($row = $results->fetchResult()) {
512
                $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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
513
                if (is_string($pk)) {
514
                    $this->getRegistry()->set($item->getPrimaryKey(), $item);
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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
515
                }
516
                if (isset($params['indexKey']) && !empty($params['indexKey'])) {
517
                    $return->add($item, $params['indexKey']);
518
                } else {
519
                    $return->add($item);
520
                }
521
            }
522
        }
523
524
        return $return;
525
    }
526
527
    /**
528
     * @param bool|array $where
529
     * @return int
530
     */
531
    public function count($where = false)
532
    {
533
        return $this->countByParams(["where" => $where]);
534
    }
535
536
    /**
537
     * Counts all the Record entries in the database
538
     * @param array $params
539
     * @return int
540
     */
541
    public function countByParams($params = [])
542
    {
543
        $this->injectParams($params);
544
        $query = $this->newQuery('select');
545
        $query->addParams($params);
546
547
        return $this->countByQuery($query);
548
    }
549
550
    /**
551
     * Counts all the Record entries in the database
552
     * @param Query $query
553
     * @return int
554
     */
555
    public function countByQuery($query)
556
    {
557
        $queryCount = clone $query;
558
        $queryCount->setCols('count(*) as count');
0 ignored issues
show
Unused Code introduced by
The call to AbstractQuery::setCols() has too many arguments starting with 'count(*) as count'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
559
        $result = $this->getDB()->execute($queryCount);
560
561
        if ($result->numRows()) {
562
            $row = $result->fetchResult();
563
564
            return (int)$row['count'];
565
        }
566
567
        return false;
568
    }
569
570
    /**
571
     * @param $data
572
     * @return mixed
573
     */
574
    public function cleanData($data)
575
    {
576
        return $this->getDB()->getAdapter()->cleanData($data);
577
    }
578
579
    /**
580
     * @param $name
581
     * @param $arguments
582
     * @return RecordCollection|null
583
     */
584
    protected function isCallDatabaseOperation($name, $arguments)
585
    {
586
        $operations = ["find", "delete", "count"];
587
        foreach ($operations as $operation) {
588
            if (strpos($name, $operation . "By") !== false || strpos($name, $operation . "OneBy") !== false) {
589
                $params = [];
590
                if (count($arguments) > 1) {
591
                    $params = end($arguments);
592
                }
593
594
                $match = str_replace([$operation . "By", $operation . "OneBy"], "", $name);
595
                $field = inflector()->underscore($match);
596
597
                if ($field == $this->getPrimaryKey()) {
598
                    return $this->findByPrimary($arguments[0]);
0 ignored issues
show
Bug introduced by
It seems like findByPrimary() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
599
                }
600
601
                $params['where'][] = ["$field " . (is_array($arguments[0]) ? "IN" : "=") . " ?", $arguments[0]];
602
603
                $operation = str_replace($match, "", $name) . "Params";
604
605
                return $this->$operation($params);
606
            }
607
        }
608
609
        return null;
610
    }
611
}
612