Completed
Pull Request — master (#7)
by Marcel
01:20
created

QueryBuilder::defaultSort()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Spatie\QueryBuilder;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Collection;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Database\Eloquent\Builder;
9
use Spatie\QueryBuilder\Exceptions\InvalidQuery;
10
11
class QueryBuilder extends Builder
12
{
13
    /** @var \Illuminate\Support\Collection */
14
    protected $allowedFilters;
15
16
    /** @var string|null */
17
    protected $defaultSort;
18
19
    /** @var \Illuminate\Support\Collection */
20
    protected $allowedSorts;
21
22
    /** @var \Illuminate\Support\Collection */
23
    protected $allowedIncludes;
24
25
    /** @var \Illuminate\Http\Request */
26
    protected $request;
27
28
    public function __construct(Builder $builder, ?Request $request = null)
29
    {
30
        parent::__construct($builder->getQuery());
31
32
        $this->setModel($builder->getModel());
33
34
        $this->request = $request ?? request();
35
36
        if ($this->request->sort()) {
37
            $this->allowedSorts('*');
38
        }
39
    }
40
41
    /**
42
     * Create a new QueryBuilder for a request and model.
43
     *
44
     * @param string|\Illuminate\Database\Query\Builder $baseQuery Model class or base query builder
45
     * @param Request $request
46
     *
47
     * @return \Spatie\QueryBuilder\QueryBuilder
48
     */
49
    public static function for($baseQuery, ?Request $request = null): self
0 ignored issues
show
Coding Style introduced by
Possible parse error: non-abstract method defined as abstract
Loading history...
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
50
    {
51
        if (is_string($baseQuery)) {
52
            $baseQuery = ($baseQuery)::query();
53
        }
54
55
        return new static($baseQuery, $request ?? request());
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
Coding Style introduced by
The visibility should be declared for property $baseQuery.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
56
    }
57
58
    public function allowedFilters(...$filters): self
59
    {
60
        $this->allowedFilters = collect($filters)->map(function ($filter) {
61
            if ($filter instanceof Filter) {
62
                return $filter;
63
            }
64
65
            return Filter::partial($filter);
66
        });
67
68
        $this->guardAgainstUnknownFilters();
69
70
        $this->addFiltersToQuery($this->request->filters());
71
72
        return $this;
73
    }
74
75
    public function defaultSort($sort): self
76
    {
77
        $this->defaultSort = $sort;
78
79
        $this->addSortToQuery($this->request->sort($this->defaultSort));
80
81
        return $this;
82
    }
83
84
    public function allowedSorts(...$sorts): self
85
    {
86
        $this->allowedSorts = collect($sorts);
87
88
        if (! $this->allowedSorts->contains('*')) {
89
            $this->guardAgainstUnknownSorts();
90
        }
91
92
        if (! is_null($this->request->sort())) {
93
            $this->addSortToQuery($this->request->sort($this->defaultSort));
94
        }
95
96
        return $this;
97
    }
98
99
    public function allowedIncludes(...$includes): self
100
    {
101
        $this->allowedIncludes = collect($includes);
102
103
        $this->guardAgainstUnknownIncludes();
104
105
        $this->addIncludesToQuery($this->request->includes());
106
107
        return $this;
108
    }
109
110
    protected function addFiltersToQuery(Collection $filters)
111
    {
112
        $filters->each(function ($value, $property) {
113
            $filter = $this->findFilter($property);
114
115
            $filter->filter($this, $value);
116
        });
117
    }
118
119
    protected function findFilter(string $property) : ?Filter
120
    {
121
        return $this->allowedFilters
122
            ->first(function (Filter $filter) use ($property) {
123
                return $filter->isForProperty($property);
124
            });
125
    }
126
127
    protected function addSortToQuery(string $sort)
128
    {
129
        $descending = $sort[0] === '-';
130
131
        $key = ltrim($sort, '-');
132
133
        $this->orderBy($key, $descending ? 'desc' : 'asc');
0 ignored issues
show
Bug introduced by
The method orderBy() does not exist on Spatie\QueryBuilder\QueryBuilder. Did you maybe mean enforceOrderBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
134
    }
135
136
    protected function addIncludesToQuery(Collection $includes)
137
    {
138
        $includes
139
            ->map(function (string $include) {
140
                return camel_case($include);
141
            })
142
            ->each(function (string $include) {
143
                $this->with($include);
144
            });
145
    }
146
147
    protected function guardAgainstUnknownFilters()
148
    {
149
        $filterNames = $this->request->filters()->keys();
150
151
        $allowedFilterNames = $this->allowedFilters->map->getProperty();
152
153
        $diff = $filterNames->diff($allowedFilterNames);
154
155
        if ($diff->count()) {
156
            throw InvalidQuery::filtersNotAllowed($diff, $allowedFilterNames);
157
        }
158
    }
159
160
    protected function guardAgainstUnknownSorts()
161
    {
162
        $sort = ltrim($this->request->sort(), '-');
163
164
        if (! $this->allowedSorts->contains($sort) && $sort !== '') {
165
            throw InvalidQuery::sortsNotAllowed($sort, $this->allowedSorts);
166
        }
167
    }
168
169
    protected function guardAgainstUnknownIncludes()
170
    {
171
        $includes = $this->request->includes();
172
173
        $diff = $includes->diff($this->allowedIncludes);
174
175
        if ($diff->count()) {
176
            throw InvalidQuery::includesNotAllowed($diff, $this->allowedIncludes);
177
        }
178
    }
179
}
180