Completed
Pull Request — master (#219)
by Dominik
01:19
created

SortsQuery::parseSorts()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

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