Completed
Pull Request — master (#103)
by
unknown
01:43
created

QueryBuilder::guardAgainstUnknownFields()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Spatie\QueryBuilder;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Collection;
7
use Illuminate\Database\Eloquent\Builder;
8
use Spatie\QueryBuilder\Exceptions\InvalidSortQuery;
9
use Spatie\QueryBuilder\Exceptions\InvalidAppendQuery;
10
use Spatie\QueryBuilder\Exceptions\InvalidFieldQuery;
11
use Spatie\QueryBuilder\Exceptions\InvalidFilterQuery;
12
use Spatie\QueryBuilder\Exceptions\InvalidIncludeQuery;
13
14
class QueryBuilder extends Builder
15
{
16
    /** @var \Illuminate\Support\Collection */
17
    protected $allowedFilters;
18
19
    /** @var \Illuminate\Support\Collection */
20
    protected $allowedFields;
21
22
    /** @var string|null */
23
    protected $defaultSort;
24
25
    /** @var \Illuminate\Support\Collection */
26
    protected $allowedSorts;
27
28
    /** @var \Illuminate\Support\Collection */
29
    protected $allowedIncludes;
30
31
    /** @var \Illuminate\Support\Collection */
32
    protected $allowedAppends;
33
34
    /** @var \Illuminate\Support\Collection */
35
    protected $fields;
36
37
    /** @var array */
38
    protected $appends = [];
39
40
    /** @var \Illuminate\Http\Request */
41
    protected $request;
42
43
    public function __construct(Builder $builder, ? Request $request = null)
44
    {
45
        parent::__construct(clone $builder->getQuery());
46
47
        $this->initializeFromBuilder($builder);
48
49
        $this->request = $request ?? request();
50
51
        $this->parseSelectedFields();
52
53
        if ($this->request->sorts()) {
54
            $this->allowedSorts('*');
55
        }
56
    }
57
58
    /**
59
     * Add the model, scopes, eager loaded relationships, local macro's and onDelete callback
60
     * from the $builder to this query builder.
61
     *
62
     * @param \Illuminate\Database\Eloquent\Builder $builder
63
     */
64
    protected function initializeFromBuilder(Builder $builder)
65
    {
66
        $this->setModel($builder->getModel())
0 ignored issues
show
Bug introduced by
It seems like $builder->getModel() targeting Illuminate\Database\Eloquent\Builder::getModel() can also be of type object<Illuminate\Database\Eloquent\Builder>; however, Illuminate\Database\Eloquent\Builder::setModel() does only seem to accept object<Illuminate\Database\Eloquent\Model>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
67
            ->setEagerLoads($builder->getEagerLoads());
68
69
        $builder->macro('getProtected', function (Builder $builder, string $property) {
70
            return $builder->{$property};
71
        });
72
73
        $this->scopes = $builder->getProtected('scopes');
74
75
        $this->localMacros = $builder->getProtected('localMacros');
76
77
        $this->onDelete = $builder->getProtected('onDelete');
78
    }
79
80
    /**
81
     * Create a new QueryBuilder for a request and model.
82
     *
83
     * @param string|\Illuminate\Database\Query\Builder $baseQuery Model class or base query builder
84
     * @param Request $request
85
     *
86
     * @return \Spatie\QueryBuilder\QueryBuilder
87
     */
88
    public static function for($baseQuery, ? Request $request = null) : self
89
    {
90
        if (is_string($baseQuery)) {
91
            $baseQuery = ($baseQuery)::query();
92
        }
93
94
        return new static($baseQuery, $request ?? request());
95
    }
96
97
    public function allowedFilters($filters) : self
98
    {
99
        $filters = is_array($filters) ? $filters : func_get_args();
100
        $this->allowedFilters = collect($filters)->map(function ($filter) {
101
            if ($filter instanceof Filter) {
102
                return $filter;
103
            }
104
105
            return Filter::partial($filter);
106
        });
107
108
        $this->guardAgainstUnknownFilters();
109
110
        $this->addFiltersToQuery($this->request->filters());
111
112
        return $this;
113
    }
114
115
    public function allowedFields($fields) : self
116
    {
117
        $fields = is_array($fields) ? $fields : func_get_args();
118
119
        $this->allowedFields = collect($fields);
120
121
        if (! $this->allowedFields->contains('*')) {
122
            $this->guardAgainstUnknownFields();
123
        }
124
125
        return $this;
126
    }
127
128
    public function defaultSort($sort) : self
129
    {
130
        $this->defaultSort = $sort;
131
132
        $this->addSortsToQuery($this->request->sorts($this->defaultSort));
133
134
        return $this;
135
    }
136
137
    public function allowedSorts($sorts) : self
138
    {
139
        $sorts = is_array($sorts) ? $sorts : func_get_args();
140
        if (! $this->request->sorts()) {
141
            return $this;
142
        }
143
144
        $this->allowedSorts = collect($sorts);
145
146
        if (! $this->allowedSorts->contains('*')) {
147
            $this->guardAgainstUnknownSorts();
148
        }
149
150
        $this->addSortsToQuery($this->request->sorts($this->defaultSort));
151
152
        return $this;
153
    }
154
155
    public function allowedIncludes($includes) : self
156
    {
157
        $includes = is_array($includes) ? $includes : func_get_args();
158
159
        $this->allowedIncludes = collect($includes)
160
            ->flatMap(function ($include) {
161
                return collect(explode('.', $include))
162
                    ->reduce(function ($collection, $include) {
163
                        if ($collection->isEmpty()) {
164
                            return $collection->push($include);
165
                        }
166
167
                        return $collection->push("{$collection->last()}.{$include}");
168
                    }, collect());
169
            });
170
171
        $this->guardAgainstUnknownIncludes();
172
173
        $this->addIncludesToQuery($this->request->includes());
174
175
        return $this;
176
    }
177
178
    public function allowedAppends($appends) : self
179
    {
180
        $appends = is_array($appends) ? $appends : func_get_args();
181
182
        $this->allowedAppends = collect($appends);
183
184
        $this->guardAgainstUnknownAppends();
185
186
        $this->appends = $this->request->appends();
187
188
        return $this;
189
    }
190
191
    protected function parseSelectedFields()
192
    {
193
        $this->fields = $this->request->fields();
194
195
        $modelTableName = $this->getModel()->getTable();
0 ignored issues
show
Bug introduced by
The method getTable does only exist in Illuminate\Database\Eloquent\Model, but not in Illuminate\Database\Eloquent\Builder.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
196
        $modelFields = $this->fields->get($modelTableName);
197
198
        if (! $modelFields) {
199
            $modelFields = '*';
200
        }
201
202
        $this->select($this->prependFieldsWithTableName(explode(',', $modelFields), $modelTableName));
0 ignored issues
show
Bug introduced by
The method select() does not exist on Spatie\QueryBuilder\QueryBuilder. Did you maybe mean parseSelectedFields()?

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...
203
    }
204
205
    protected function prependFieldsWithTableName(array $fields, string $tableName): array
206
    {
207
        return array_map(function ($field) use ($tableName) {
208
            return "{$tableName}.{$field}";
209
        }, $fields);
210
    }
211
212
    protected function getFieldsForRelatedTable(string $relation): array
213
    {
214
        $fields = $this->fields->get($relation);
215
216
        if (! $fields) {
217
            return [];
218
        }
219
220
        return explode(',', $fields);
221
    }
222
223
    protected function addFiltersToQuery(Collection $filters)
224
    {
225
        $filters->each(function ($value, $property) {
226
            $filter = $this->findFilter($property);
227
228
            $filter->filter($this, $value);
229
        });
230
    }
231
232
    protected function findFilter(string $property) : ? Filter
233
    {
234
        return $this->allowedFilters
235
            ->first(function (Filter $filter) use ($property) {
236
                return $filter->isForProperty($property);
237
            });
238
    }
239
240
    protected function addSortsToQuery(Collection $sorts)
241
    {
242
        $this->filterDuplicates($sorts)
243
            ->each(function (string $sort) {
244
                $descending = $sort[0] === '-';
245
246
                $key = ltrim($sort, '-');
247
248
                $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...
249
            });
250
    }
251
252
    protected function filterDuplicates(Collection $sorts): Collection
253
    {
254
        if (! is_array($orders = $this->getQuery()->orders)) {
255
            return $sorts;
256
        }
257
258
        return $sorts->reject(function (string $sort) use ($orders) {
259
            $toSort = [
260
                'column' => ltrim($sort, '-'),
261
                'direction' => ($sort[0] === '-') ? 'desc' : 'asc',
262
            ];
263
            foreach ($orders as $order) {
264
                if ($order === $toSort) {
265
                    return true;
266
                }
267
            }
268
        });
269
    }
270
271
    protected function addIncludesToQuery(Collection $includes)
272
    {
273
        $includes
274
            ->map('camel_case')
275
            ->map(function (string $include) {
276
                return collect(explode('.', $include));
277
            })
278
            ->flatMap(function (Collection $relatedTables) {
279
                return $relatedTables
280
                    ->mapWithKeys(function ($table, $key) use ($relatedTables) {
281
                        $fields = $this->getFieldsForRelatedTable(snake_case($table));
282
283
                        $fullRelationName = $relatedTables->slice(0, $key + 1)->implode('.');
284
285
                        if (empty($fields)) {
286
                            return [$fullRelationName];
287
                        }
288
289
                        return [$fullRelationName => function ($query) use ($fields) {
290
                            $query->select($fields);
291
                        }];
292
                    });
293
            })
294
            ->pipe(function (Collection $withs) {
295
                $this->with($withs->all());
296
            });
297
    }
298
299
    public function setAppendsToResult($result)
300
    {
301
        $result->map(function ($item) {
302
            $item->append($this->appends->toArray());
0 ignored issues
show
Bug introduced by
The method toArray cannot be called on $this->appends (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
303
304
            return $item;
305
        });
306
307
        return $result;
308
    }
309
310
    protected function guardAgainstUnknownFilters()
311
    {
312
        $filterNames = $this->request->filters()->keys();
313
314
        $allowedFilterNames = $this->allowedFilters->map->getProperty();
315
316
        $diff = $filterNames->diff($allowedFilterNames);
317
318
        if ($diff->count()) {
319
            throw InvalidFilterQuery::filtersNotAllowed($diff, $allowedFilterNames);
320
        }
321
    }
322
323
    protected function guardAgainstUnknownFields()
324
    {
325
        $fields = $this->request->fields()->flatMap(function ($value) {
326
            return explode(',', $value);
327
        })->unique();
328
329
        $diff = $fields->diff($this->allowedFields);
330
331
        if ($diff->count()) {
332
            throw InvalidFieldQuery::fieldsNotAllowed($diff, $this->allowedFields);
333
        }
334
    }
335
336
    protected function guardAgainstUnknownSorts()
337
    {
338
        $sorts = $this->request->sorts()->map(function ($sort) {
339
            return ltrim($sort, '-');
340
        });
341
342
        $diff = $sorts->diff($this->allowedSorts);
343
344
        if ($diff->count()) {
345
            throw InvalidSortQuery::sortsNotAllowed($diff, $this->allowedSorts);
346
        }
347
    }
348
349
    protected function guardAgainstUnknownIncludes()
350
    {
351
        $includes = $this->request->includes();
352
353
        $diff = $includes->diff($this->allowedIncludes);
354
355
        if ($diff->count()) {
356
            throw InvalidIncludeQuery::includesNotAllowed($diff, $this->allowedIncludes);
357
        }
358
    }
359
360
    protected function guardAgainstUnknownAppends()
361
    {
362
        $appends = $this->request->appends();
363
364
        $diff = $appends->diff($this->allowedAppends);
365
366
        if ($diff->count()) {
367
            throw InvalidAppendQuery::appendsNotAllowed($diff, $this->allowedAppends);
368
        }
369
    }
370
371
    public function get($columns = ['*'])
372
    {
373
        $result = parent::get($columns);
374
375
        if (count($this->appends) > 0) {
376
            $result = $this->setAppendsToResult($result);
377
        }
378
379
        return $result;
380
    }
381
}
382