/
Sprunje.php
577 lines (494 loc) · 15.3 KB
/
Sprunje.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
<?php
/*
* UserFrosting (http://www.userfrosting.com)
*
* @link https://github.com/userfrosting/UserFrosting
* @copyright Copyright (c) 2019 Alexander Weissman
* @license https://github.com/userfrosting/UserFrosting/blob/master/LICENSE.md (MIT License)
*/
namespace UserFrosting\Sprinkle\Core\Sprunje;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use League\Csv\Writer;
use Psr\Http\Message\ResponseInterface as Response;
use UserFrosting\Sprinkle\Core\Util\ClassMapper;
use UserFrosting\Support\Exception\BadRequestException;
use Valitron\Validator;
/**
* Sprunje.
*
* Implements a versatile API for sorting, filtering, and paginating an Eloquent query builder.
*
* @author Alex Weissman (https://alexanderweissman.com)
*/
abstract class Sprunje
{
/**
* @var ClassMapper
*/
protected $classMapper;
/**
* Name of this Sprunje, used when generating output files.
*
* @var string
*/
protected $name = '';
/**
* The base (unfiltered) query.
*
* @var \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation
*/
protected $query;
/**
* Default HTTP request parameters.
*
* @var array<string,mixed>
*/
protected $options = [
'sorts' => [],
'filters' => [],
'lists' => [],
'size' => 'all',
'page' => null,
'format' => 'json',
];
/**
* Fields to allow filtering upon.
*
* @var string[]
*/
protected $filterable = [];
/**
* Fields to allow listing (enumeration) upon.
*
* @var string[]
*/
protected $listable = [];
/**
* Fields to allow sorting upon.
*
* @var string[]
*/
protected $sortable = [];
/**
* List of fields to exclude when processing an "_all" filter.
*
* @var string[]
*/
protected $excludeForAll = [];
/**
* Separator to use when splitting filter values to treat them as ORs.
*
* @var string
*/
protected $orSeparator = '||';
/**
* Array key for the total unfiltered object count.
*
* @var string
*/
protected $countKey = 'count';
/**
* Array key for the filtered object count.
*
* @var string
*/
protected $countFilteredKey = 'count_filtered';
/**
* Array key for the actual result set.
*
* @var string
*/
protected $rowsKey = 'rows';
/**
* Array key for the list of enumerated columns and their enumerations.
*
* @var string
*/
protected $listableKey = 'listable';
/**
* Constructor.
*
* @param ClassMapper $classMapper
* @param mixed[] $options
*/
public function __construct(ClassMapper $classMapper, array $options)
{
$this->classMapper = $classMapper;
// Validation on input data
$v = new Validator($options);
$v->rule('array', ['sorts', 'filters', 'lists']);
$v->rule('regex', 'sorts.*', '/asc|desc/i');
$v->rule('regex', 'size', '/all|[0-9]+/i');
$v->rule('integer', 'page');
$v->rule('regex', 'format', '/json|csv/i');
// TODO: translated rules
if (!$v->validate()) {
$e = new BadRequestException();
foreach ($v->errors() as $idx => $field) {
foreach ($field as $eidx => $error) {
$e->addUserMessage($error);
}
}
throw $e;
}
$this->options = array_replace_recursive($this->options, $options);
$this->query = $this->baseQuery();
// Start a new query on any Model instances
if (is_a($this->baseQuery(), '\Illuminate\Database\Eloquent\Model')) {
$this->query = $this->baseQuery()->newQuery();
}
}
/**
* Extend the query by providing a callback.
*
* @param callable $callback A callback which accepts and returns a Builder instance.
*
* @return self
*/
public function extendQuery(callable $callback)
{
$this->query = $callback($this->query);
return $this;
}
/**
* Execute the query and build the results, and append them in the appropriate format to the response.
*
* @param Response $response
*
* @return Response
*/
public function toResponse(Response $response)
{
$format = $this->options['format'];
if ($format == 'csv') {
$result = $this->getCsv();
// Prepare response
$response = $response->withAddedHeader('Content-Disposition', "attachment;filename={$this->name}.csv");
$response = $response->withAddedHeader('Content-Type', 'text/csv; charset=utf-8');
return $response->write($result);
// Default to JSON
} else {
$result = $this->getArray();
return $response->withJson($result, 200, JSON_PRETTY_PRINT);
}
}
/**
* Executes the sprunje query, applying all sorts, filters, and pagination.
*
* Returns an array containing `count` (the total number of rows, before filtering), `count_filtered` (the total number of rows after filtering),
* and `rows` (the filtered result set).
*
* @return mixed[]
*/
public function getArray()
{
list($count, $countFiltered, $rows) = $this->getModels();
// Return sprunjed results
return [
$this->countKey => $count,
$this->countFilteredKey => $countFiltered,
$this->rowsKey => $rows->values()->toArray(),
$this->listableKey => $this->getListable(),
];
}
/**
* Run the query and build a CSV object by flattening the resulting collection. Ignores any pagination.
*
* @return Writer
*/
public function getCsv()
{
$filteredQuery = clone $this->query;
// Apply filters
$this->applyFilters($filteredQuery);
// Apply sorts
$this->applySorts($filteredQuery);
$collection = collect($filteredQuery->get());
// Perform any additional transformations on the dataset
$collection = $this->applyTransformations($collection);
$csv = Writer::createFromFileObject(new \SplTempFileObject());
$columnNames = [];
// Flatten collection while simultaneously building the column names from the union of each element's keys
$collection->transform(function ($item, $key) use (&$columnNames) {
$item = Arr::dot($item->toArray());
foreach ($item as $itemKey => $itemValue) {
if (!in_array($itemKey, $columnNames)) {
$columnNames[] = $itemKey;
}
}
return $item;
});
$csv->insertOne($columnNames);
// Insert the data as rows in the CSV document
$collection->each(function ($item) use ($csv, $columnNames) {
$row = [];
foreach ($columnNames as $itemKey) {
// Only add the value if it is set and not an array. Laravel's array_dot sometimes creates empty child arrays :(
// See https://github.com/laravel/framework/pull/13009
if (isset($item[$itemKey]) && !is_array($item[$itemKey])) {
$row[] = $item[$itemKey];
} else {
$row[] = '';
}
}
$csv->insertOne($row);
});
return $csv;
}
/**
* Executes the sprunje query, applying all sorts, filters, and pagination.
*
* Returns the filtered, paginated result set and the counts.
*
* @return mixed[]
*/
public function getModels()
{
// Count unfiltered total
$count = $this->count($this->query);
// Clone the Query\Builder, Eloquent\Builder, or Relation
$filteredQuery = clone $this->query;
// Apply filters
$this->applyFilters($filteredQuery);
// Count filtered total
$countFiltered = $this->countFiltered($filteredQuery);
// Apply sorts
$this->applySorts($filteredQuery);
// Paginate
$this->applyPagination($filteredQuery);
$collection = collect($filteredQuery->get());
// Perform any additional transformations on the dataset
$collection = $this->applyTransformations($collection);
return [$count, $countFiltered, $collection];
}
/**
* Get lists of values for specified fields in 'lists' option, calling a custom lister callback when appropriate.
*
* @return array<string,mixed>
*/
public function getListable()
{
$result = [];
foreach ($this->listable as $name) {
// Determine if a custom filter method has been defined
$methodName = 'list' . Str::studly($name);
if (method_exists($this, $methodName)) {
$result[$name] = $this->$methodName();
} else {
$result[$name] = $this->getColumnValues($name);
}
}
return $result;
}
/**
* Get the underlying queriable object in its current state.
*
* @return Builder
*/
public function getQuery()
{
return $this->query;
}
/**
* Set the underlying QueryBuilder object.
*
* @param Builder $query
*
* @return self
*/
public function setQuery($query)
{
$this->query = $query;
return $this;
}
/**
* Apply any filters from the options, calling a custom filter callback when appropriate.
*
* @param Builder $query
*
* @return self
*/
public function applyFilters($query)
{
foreach ($this->options['filters'] as $name => $value) {
// Check that this filter is allowed
if (($name != '_all') && !in_array($name, $this->filterable)) {
$e = new BadRequestException();
$e->addUserMessage('VALIDATE.SPRUNJE.BAD_FILTER', ['name' => $name]);
throw $e;
}
// Since we want to match _all_ of the fields, we wrap the field callback in a 'where' callback
$query->where(function ($fieldQuery) use ($name, $value) {
$this->buildFilterQuery($fieldQuery, $name, $value);
});
}
return $this;
}
/**
* Apply any sorts from the options, calling a custom sorter callback when appropriate.
*
* @param Builder $query
*
* @return self
*/
public function applySorts($query)
{
foreach ($this->options['sorts'] as $name => $direction) {
// Check that this sort is allowed
if (!in_array($name, $this->sortable)) {
$e = new BadRequestException();
$e->addUserMessage('VALIDATE.SPRUNJE.BAD_SORT', ['name' => $name]);
throw $e;
}
// Determine if a custom sort method has been defined
$methodName = 'sort' . Str::studly($name);
if (method_exists($this, $methodName)) {
$this->$methodName($query, $direction);
} else {
$query->orderBy($name, $direction);
}
}
return $this;
}
/**
* Apply pagination based on the `page` and `size` options.
*
* @param Builder $query
*
* @return self
*/
public function applyPagination($query)
{
if (
($this->options['page'] !== null) &&
($this->options['size'] !== null) &&
($this->options['size'] != 'all')
) {
$offset = $this->options['size'] * $this->options['page'];
$query->skip($offset)
->take($this->options['size']);
}
return $this;
}
/**
* Match any filter in `filterable`.
*
* @param Builder $query
* @param mixed $value
*
* @return self
*/
protected function filterAll($query, $value)
{
foreach ($this->filterable as $name) {
if (Str::studly($name) != 'all' && !in_array($name, $this->excludeForAll)) {
// Since we want to match _any_ of the fields, we wrap the field callback in a 'orWhere' callback
$query->orWhere(function ($fieldQuery) use ($name, $value) {
$this->buildFilterQuery($fieldQuery, $name, $value);
});
}
}
return $this;
}
/**
* Build the filter query for a single field.
*
* @param Builder $query
* @param string $name
* @param mixed $value
*
* @return self
*/
protected function buildFilterQuery($query, $name, $value)
{
$methodName = 'filter' . Str::studly($name);
// Determine if a custom filter method has been defined
if (method_exists($this, $methodName)) {
$this->$methodName($query, $value);
} else {
$this->buildFilterDefaultFieldQuery($query, $name, $value);
}
return $this;
}
/**
* Perform a 'like' query on a single field, separating the value string on the or separator and
* matching any of the supplied values.
*
* @param Builder $query
* @param string $name
* @param mixed $value
*
* @return self
*/
protected function buildFilterDefaultFieldQuery($query, $name, $value)
{
// Default filter - split value on separator for OR queries
// and search by column name
$values = explode($this->orSeparator, $value);
foreach ($values as $value) {
$query->orLike($name, $value);
}
return $this;
}
/**
* Set any transformations you wish to apply to the collection, after the query is executed.
*
* @param \Illuminate\Support\Collection $collection
*
* @return \Illuminate\Support\Collection
*/
protected function applyTransformations($collection)
{
return $collection;
}
/**
* Set the initial query used by your Sprunje.
*
* @return Builder|\Illuminate\Database\Eloquent\Relations\Relation|\UserFrosting\Sprinkle\Core\Database\Models\Model
*/
abstract protected function baseQuery();
/**
* Returns a list of distinct values for a specified column.
* Formats results to have a "value" and "text" attribute.
*
* @param string $column
*
* @return array<array<string,mixed>>
*/
protected function getColumnValues($column)
{
$rawValues = $this->query->select($column)->distinct()->orderBy($column, 'asc')->get();
$values = [];
foreach ($rawValues as $raw) {
$values[] = [
'value' => $raw[$column],
'text' => $raw[$column],
];
}
return $values;
}
/**
* Get the unpaginated count of items (before filtering) in this query.
*
* @param Builder $query
*
* @return int
*/
protected function count($query)
{
return $query->count();
}
/**
* Get the unpaginated count of items (after filtering) in this query.
*
* @param Builder $query
*
* @return int
*/
protected function countFiltered($query)
{
return $query->count();
}
}