Completed
Push — master ( 62a574...40c09d )
by
unknown
01:52
created

SortsQuery::addDefaultSorts()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 2
nc 1
nop 0
1
<?php
2
3
namespace Spatie\QueryBuilder\Concerns;
4
5
use Illuminate\Support\Collection;
6
use Spatie\QueryBuilder\Exceptions\InvalidSortQuery;
7
use Spatie\QueryBuilder\Sort;
8
9
trait SortsQuery
10
{
11
    /** @var \Illuminate\Support\Collection */
12
    protected $defaultSorts;
13
14
    /** @var \Illuminate\Support\Collection */
15
    protected $allowedSorts;
16
17
    public function allowedSorts($sorts): self
18
    {
19
        $sorts = is_array($sorts) ? $sorts : func_get_args();
20
21
        if (! $this->request->sorts()) {
0 ignored issues
show
Bug introduced by
The property request 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...
22
            return $this;
23
        }
24
25
        $this->allowedSorts = collect($sorts)->map(function ($sort) {
26
            if ($sort instanceof Sort) {
27
                return $sort;
28
            }
29
30
            return Sort::field(ltrim($sort, '-'));
31
        });
32
33
        $this->guardAgainstUnknownSorts();
34
35
        $this->parseSorts();
36
37
        return $this;
38
    }
39
40
    /**
41
     * @param array|string|\Spatie\QueryBuilder\Sort $sorts
42
     *
43
     * @return \Spatie\QueryBuilder\QueryBuilder
44
     */
45
    public function defaultSort($sorts): self
0 ignored issues
show
Unused Code introduced by
The parameter $sorts 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...
46
    {
47
        return $this->defaultSorts(func_get_args());
48
    }
49
50
    /**
51
     * @param array|string|\Spatie\QueryBuilder\Sort $sorts
52
     *
53
     * @return \Spatie\QueryBuilder\QueryBuilder
54
     */
55
    public function defaultSorts($sorts): self
56
    {
57
        $sorts = is_array($sorts) ? $sorts : func_get_args();
58
59
        $this->defaultSorts = collect($sorts)->map(function ($sort) {
60
            if (is_string($sort)) {
61
                return Sort::field($sort);
62
            }
63
64
            return $sort;
65
        });
66
67
        $this->parseSorts();
68
69
        return $this;
70
    }
71
72
    protected function parseSorts()
73
    {
74
        $sorts = $this->request->sorts();
75
76
        if ($sorts->isEmpty()) {
77
            optional($this->defaultSorts)->each(function (Sort $sort) {
78
                $sort->sort($this);
79
            });
80
        }
81
82
        $this
83
            ->filterDuplicates($sorts)
84
            ->each(function (string $property) {
85
                $descending = $property[0] === '-';
86
87
                $key = ltrim($property, '-');
88
89
                $sort = $this->findSort($key);
90
91
                $sort->sort($this, $descending);
92
            });
93
    }
94
95
    protected function findSort(string $property): ?Sort
96
    {
97
        return $this->allowedSorts
98
            ->merge($this->defaultSorts)
99
            ->first(function (Sort $sort) use ($property) {
100
                return $sort->isForProperty($property);
101
            });
102
    }
103
104
    protected function addDefaultSorts()
105
    {
106
        $this->allowedSorts = collect($this->request->sorts($this->defaultSorts))
107
            ->map(function ($sort) {
108
                if ($sort instanceof Sort) {
109
                    return $sort;
110
                }
111
112
                return Sort::field(ltrim($sort, '-'));
113
            });
114
115
        $this->parseSorts();
116
    }
117
118
    protected function guardAgainstUnknownSorts()
119
    {
120
        $sortNames = $this->request->sorts()->map(function ($sort) {
121
            return ltrim($sort, '-');
122
        });
123
124
        $allowedSortNames = $this->allowedSorts->map->getProperty();
125
126
        $diff = $sortNames->diff($allowedSortNames);
127
128
        if ($diff->count()) {
129
            throw InvalidSortQuery::sortsNotAllowed($diff, $allowedSortNames);
130
        }
131
    }
132
133
    protected function filterDuplicates(Collection $sorts): Collection
134
    {
135
        if (! is_array($orders = $this->getQuery()->orders)) {
0 ignored issues
show
Bug introduced by
It seems like getQuery() 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...
136
            return $sorts;
137
        }
138
139
        return $sorts->reject(function (string $sort) use ($orders) {
140
            $toSort = [
141
                'column' => ltrim($sort, '-'),
142
                'direction' => ($sort[0] === '-') ? 'desc' : 'asc',
143
            ];
144
            foreach ($orders as $order) {
145
                if ($order === $toSort) {
146
                    return true;
147
                }
148
            }
149
        });
150
    }
151
}
152