Passed
Push — master ( 4688c8...2d21c0 )
by Andrey
12:30
created

Search::by()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 4
c 1
b 1
f 0
nc 1
nop 2
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Helldar\Roles\Support\Database;
4
5
use Helldar\Roles\Models\BaseModel;
6
use Illuminate\Contracts\Support\Arrayable;
7
use Illuminate\Support\Arr;
8
use Illuminate\Support\Collection;
9
10
class Search
11
{
12
    /**
13
     * @param  \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation  $builder
14
     * @param  \Helldar\Roles\Models\BaseModel|string|int  $values
15
     *
16
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation
17
     */
18
    public function by($builder, $values)
19
    {
20
        $value = $this->map($values);
21
22
        return $builder
0 ignored issues
show
Bug Best Practice introduced by
The expression return $builder->whereIn...WhereIn('name', $value) also could return the type Illuminate\Database\Query\Builder which is incompatible with the documented return type Illuminate\Database\Eloq...uent\Relations\Relation.
Loading history...
23
            ->whereIn('id', $value)
24
            ->orWhereIn('name', $value);
25
    }
26
27
    /**
28
     * @param  \Helldar\Roles\Models\BaseModel|string|int  $value
29
     *
30
     * @return int|string
31
     */
32
    public function getId($value)
33
    {
34
        return $value instanceof BaseModel
35
            ? $value->id
36
            : $value;
37
    }
38
39
    /**
40
     * @param  Collection|Arrayable|array|string|int  $values
41
     *
42
     * @return array
43
     */
44
    protected function map($values): array
45
    {
46
        return array_map(function ($value) {
47
            return $this->getId($value);
48
        }, $this->toArray($values));
49
    }
50
51
    protected function toArray($values): array
52
    {
53
        if ($this->isArrayable($values)) {
54
            $values = $values->toArray();
55
        } elseif (! $this->isArray($values)) {
56
            $values = Arr::wrap($values);
57
        }
58
59
        return Arr::flatten($values);
60
    }
61
62
    protected function isArray($values): bool
63
    {
64
        return is_array($values);
65
    }
66
67
    protected function isArrayable($values): bool
68
    {
69
        return $values instanceof Arrayable || $values instanceof Collection;
70
    }
71
}
72