DatabaseBuilder::search()   B
last analyzed

Complexity

Conditions 7
Paths 1

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 7
eloc 19
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 35
rs 8.8333
1
<?php
2
3
namespace FaithGen\SDK\Mixins;
4
5
use Illuminate\Support\Str;
6
7
class DatabaseBuilder
8
{
9
    /**
10
     * Searches the database in an eloquent query for the given attributes.
11
     *
12
     * @return \Closure
13
     */
14
    public function search()
15
    {
16
        return function ($attributes, ?string $filter_text) {
17
            if ($filter_text) {
18
                $filter_text = '%'.$filter_text.'%';
19
            }
20
21
            if (is_string($attributes)) {
22
                return $this->where($attributes, 'LIKE', $filter_text);
0 ignored issues
show
Bug introduced by
The method where() does not exist on FaithGen\SDK\Mixins\DatabaseBuilder. ( Ignorable by Annotation )

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

22
                return $this->/** @scrutinizer ignore-call */ where($attributes, 'LIKE', $filter_text);

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...
23
            }
24
25
            if (is_array($attributes)) {
26
                $attributes = collect($attributes);
27
28
                $attribute = $attributes->first();
29
30
                $remainderKeys = $attributes->filter(fn ($field) => $field !== $attribute)->toArray();
31
32
                $query = $this->where($attribute, 'LIKE', $filter_text);
33
34
                if (count($remainderKeys)) {
35
                    foreach ($remainderKeys as $key) {
36
                        if (! Str::of($key)->contains('.')) {
37
                            $query->orWhere($key, 'LIKE', $filter_text);
38
                        } else {
39
                            [$relationship, $column] = explode('.', $key);
0 ignored issues
show
Comprehensibility Best Practice introduced by
This list assign is not used and could be removed.
Loading history...
40
41
                            // $eloquentBuilder->orWhereHas($relationship, fn($model) => $model->where($column, 'LIKE', $filter_text));
42
                        }
43
                    }
44
                }
45
46
                return $query;
47
            } else {
48
                abort(402, 'Invalid search fields');
49
            }
50
        };
51
    }
52
}
53