SearchTrait::buildSearchConditions()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
nc 2
nop 2
dl 0
loc 13
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Jidaikobo\Kontiki\Models\BaseModelTraits;
4
5
use Illuminate\Database\Query\Builder;
6
7
trait SearchTrait
8
{
9
    /**
10
     * Get searchable fields from the model's properties.
11
     *
12
     * @return array
13
     */
14
    protected function getSearchableFields(): array
15
    {
16
        $searchableColumns = [];
17
        foreach ($this->getFieldDefinitions() as $column => $config) {
0 ignored issues
show
Bug introduced by
It seems like getFieldDefinitions() 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

17
        foreach ($this->/** @scrutinizer ignore-call */ getFieldDefinitions() as $column => $config) {
Loading history...
18
            if (isset($config['searchable']) && $config['searchable'] === true) {
19
                $searchableColumns[] = $column;
20
            }
21
        }
22
        return $searchableColumns;
23
    }
24
25
    protected function getAdditionalConditions(Builder $query, string $context = 'all'): Builder
0 ignored issues
show
Unused Code introduced by
The parameter $context 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

25
    protected function getAdditionalConditions(Builder $query, /** @scrutinizer ignore-unused */ string $context = 'all'): Builder

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...
26
    {
27
        return $query;
28
    }
29
30
    public function buildSearchConditions(Builder $query, string $keyword = ''): Builder
31
    {
32
        if (!empty($keyword)) {
33
            $searchableColumns = $this->getSearchableFields();
34
35
            $query->where(function ($q) use ($keyword, $searchableColumns) {
36
                foreach ($searchableColumns as $column) {
37
                    $q->orWhere($column, 'LIKE', "%{$keyword}%");
38
                }
39
            });
40
        }
41
42
        return $query;
43
    }
44
}
45