-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFilterable.php
More file actions
937 lines (816 loc) · 21.4 KB
/
Filterable.php
File metadata and controls
937 lines (816 loc) · 21.4 KB
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
<?php
namespace Kettasoft\Filterable;
use Illuminate\Http\Request;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Support\Facades\App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Database\Eloquent\Builder;
use Kettasoft\Filterable\Foundation\Invoker;
use Kettasoft\Filterable\Foundation\Resources;
use Kettasoft\Filterable\Contracts\Validatable;
use Kettasoft\Filterable\Contracts\Authorizable;
use Kettasoft\Filterable\Sanitization\Sanitizer;
use Kettasoft\Filterable\Engines\Foundation\Engine;
use Kettasoft\Filterable\Foundation\Sorting\Sorter;
use Kettasoft\Filterable\Contracts\FilterableContext;
use Kettasoft\Filterable\Engines\Factory\EngineManager;
use Kettasoft\Filterable\Foundation\Contracts\Sortable;
use Kettasoft\Filterable\Foundation\FilterableSettings;
use Kettasoft\Filterable\Exceptions\MissingBuilderException;
use Kettasoft\Filterable\Engines\Foundation\Executors\Executer;
use Kettasoft\Filterable\Foundation\Contracts\Sorting\Invokable;
use Kettasoft\Filterable\Foundation\Events\FilterableEventManager;
use Kettasoft\Filterable\HttpIntegration\HeaderDrivenEngineSelector;
use Kettasoft\Filterable\Foundation\Contracts\ShouldReturnQueryBuilder;
use Kettasoft\Filterable\Exceptions\RequestSourceIsNotSupportedException;
use Kettasoft\Filterable\Foundation\Contracts\FilterableProfile;
use Kettasoft\Filterable\Foundation\Events\Contracts\EventManager;
class Filterable implements FilterableContext, Authorizable, Validatable
{
use Traits\InteractsWithFilterKey,
Traits\InteractsWithMethodMentoring,
Traits\InteractsWithFilterAuthorization,
Traits\InteractsWithValidation,
Traits\InteractsWithRelationsFiltering,
Traits\HasFilterableEvents,
Traits\InteractsWithProvidedData,
Traits\HasFilterableCache,
Macroable;
/**
* The running filter engine.
* @var Engine
*/
protected Engine $engine;
/**
* Resources instance.
* @var Resources
*/
protected Resources $resources;
/**
* Registered filters to operate upon.
* @var array
*/
protected $filters = [];
/**
* Ignore empty or null values option.
* @var bool
*/
protected $ignoreEmptyValues;
/**
* The Request instance.
* @var Request
*/
protected Request $request;
/**
* Request source.
* @var string|null
*/
protected $requestSource = 'query';
/**
* The Builder instance.
* @var Builder
*/
protected Builder $builder;
/**
* Registered sanitizers to operate upon.
* @var array
*/
protected $sanitizers = [];
/**
* All received data from request.
* @var array
*/
protected $data = [];
/**
* Specify which fields are allowed to be filtered.
* @var array
*/
protected $allowedFields = [];
/**
* List of supported SQL operators you want to allow when parsing the expressions.
* @var array
*/
protected $allowedOperators = [];
/**
* Strict mode.
* @var bool|null
*/
protected $strict;
/**
* The field name mapping.
* @var array
*/
protected $fieldsMap = [];
/**
* Registered model.
* @var Model
*/
protected $model;
/**
* Aliases of filter class
* @var array
*/
protected static $aliases;
/**
* The Sanitizer instance.
* @var Sanitizer
*/
public Sanitizer $sanitizer;
/**
* Sorters for each filterable.
* @var array<string, callable<Sorter>>
*/
protected static array $sorters = [];
/**
* @var bool
*/
protected $shouldReturnQueryBuilder = false;
/**
* Event manager instance.
* @var EventManager
*/
protected static EventManager $eventManager;
/**
* Create a new Filterable instance.
* @param Request|null $request
*/
public function __construct(Request|null $request = null)
{
$this->boot($request);
$this->booting();
$this->booted();
}
/**
* Initialize core dependencies and fire the initializing event.
*
* @return void
*/
public function boot($request = null)
{
$this->request = $request ?: App::make(Request::class);
$this->registerEventManager();
// Fire initializing event
$this->fireEvent('filterable.initializing', ['filterable' => $this]);
}
/**
* Prepare engine and internal components.
*
* @return void
*/
public function booting()
{
$this->sanitizer = new Sanitizer($this->sanitizers);
$this->resources = new Resources($this->settings());
$this->resolveEngine();
$this->parseIncomingRequestData();
}
/**
* Finalize setup and fire the booted event.
*
* @return void
*/
public function booted()
{
// Fire resolved event after initialization is complete
$this->fireEvent('filterable.resolved', [
'engine' => $this->engine,
'data' => $this->data,
]);
}
/**
* Get request source.
*
* @return string
*/
public function getRequestSource(): string
{
return $this->requestSource;
}
/**
* Apply a filterable profile to the current instance.
*
* @param FilterableProfile|string $profile
* @return static
*/
public function useProfile(FilterableProfile|callable|string $profile): static
{
// Handle callable or FilterableProfile instance directly
if (is_callable($profile)) {
$profile($this);
return $this;
}
if ($profile instanceof FilterableProfile) {
$profile($this);
return $this;
}
// Handle string references (class name or config key)
if (is_string($profile)) {
$profiles = config('filterable.profiles', []);
$resolved = $profiles[$profile] ?? $profile;
// If still not found or invalid, return as-is
if (!class_exists($resolved)) {
return $this;
}
$instance = App::make($resolved);
if (is_callable($instance)) {
$instance($this);
}
return $this;
}
return $this;
}
/**
* Register the event manager instance.
* @param array $options
* @return void
*/
private function registerEventManager(array $options = [])
{
self::$eventManager = App::make(FilterableEventManager::class, $options);
}
/**
* Get Resources instance.
* @return Resources
*/
public function getResources(): Resources
{
return $this->resources;
}
/**
* Get FilterableSettings instance.
* @return FilterableSettings
*/
public function settings(): FilterableSettings
{
return FilterableSettings::init(
$this->allowedFields,
$this->relations,
$this->allowedOperators,
$this->sanitizers,
$this->fieldsMap
);
}
/**
* Apply all filters.
*
* @param Builder $builder
* @return Builder|Invoker
*/
public function apply(Builder|null $builder = null): Invoker|Builder
{
try {
App::make(Pipeline::class)->send($this)->through([
\Kettasoft\Filterable\Pipes\FilterAuthorizationPipe::class,
\Kettasoft\Filterable\Pipes\ValidateBeforeFilteringPipe::class
])->thenReturn();
$builder = $this->initQueryBuilderInstance($builder);
$this->builder = $this->initially($builder);
$builder = Executer::execute($this->engine, $builder);
if (isset(self::$sorters[static::class])) {
$builder = static::getSorting(static::class)?->apply($builder);
}
// Fire applied event on success
$this->fireEvent('filterable.applied', [
'filterable' => $this
]);
if ($this instanceof ShouldReturnQueryBuilder || $this->shouldReturnQueryBuilder) {
return $builder;
}
$invoker = new Invoker($this->finally($builder));
// Pass caching settings to invoker
if ($this->isCachingEnabled()) {
$invoker->enableCaching(
$this->generateCacheKey(),
$this->getCacheTtl(),
$this->getCacheTags(),
$this->cacheForever
);
}
return $invoker;
} catch (\Throwable $exception) {
// Fire failed event on exception
$this->fireEvent('filterable.failed', [
'exception' => $exception,
'filterable' => $this,
]);
// Re-throw the exception after firing the event
throw $exception;
} finally {
// Always fire finished event
$this->fireEvent('filterable.finished', [
'filterable' => $this,
]);
}
}
/**
* Finalize the query builder after all filters have been applied.
*
* @param Builder $builder
* @return Builder
*/
protected function finally(Builder $builder): Builder
{
// Custom finalization logic can be added here
return $builder;
}
/**
* Initial processing of the query builder before applying filters.
*
* @param Builder $builder
* @return Builder
*/
protected function initially(Builder $builder): Builder
{
// Custom initial logic can be added here
return $builder;
}
/**
* Create and return a new Filterable instance after applying the given callback.
*
* @param callable \Closure(static): void $callback A callback that receives the instance for configuration.
* @return static
*/
public static function tap(callable $callback, $instance = null): static
{
$instance = $instance ?: new static;
$callback($instance);
return $instance;
}
/**
* Add a sorting callback for a specific filterable.
*
* @param string|array $filterable
* @param callable $callback
* @return void
*/
public static function addSorting(string|array $filterable, callable|string|Invokable $callback, Request|null $request = null): void
{
if (is_string($filterable)) {
$filterable = [$filterable];
}
foreach ($filterable as $filter) {
if (is_string($callback) && class_exists($callback) && is_subclass_of($callback, Invokable::class)) {
$callback = app($callback, ['request' => $request ?: app('request')]);
return;
}
if (!is_callable($callback) && !$callback instanceof Invokable) {
throw new \InvalidArgumentException('The sorting callback must be a callable or an instance of ' . Invokable::class);
}
$request = $request ?: app('request');
self::$sorters[$filter] = $callback(new Sorter($request), $request);
}
}
/**
* Define sorting rules for the current filterable instance.
*
* @param callable $sorting
* @return static
*/
public function sorting(callable|string|Invokable $sorting): static
{
static::addSorting(static::class, $sorting);
return $this;
}
/**
* Get sorting rules for a Filterable class.
*
* @param string $filterClass
* @return Sortable|null
*/
public static function getSorting(string $filterClass): ?Sortable
{
return static::$sorters[$filterClass] ?? null;
}
/**
* Should return Query Builder instance when invoke `@apply`
* @return static
*/
public function shouldReturnQueryBuilder()
{
$this->shouldReturnQueryBuilder = true;
return $this;
}
/**
* Alias name for @apply method.
* @param \Illuminate\Database\Eloquent\Builder|null $builder
* @return Invoker|Builder
*/
public function filter(Builder|null $builder = null): Invoker|Builder
{
return $this->apply($builder);
}
/**
* Get all aliases.
* @return array
*/
public static function aliases(array $aliases)
{
self::$aliases = $aliases;
return self::$aliases;
}
/**
* Initialize query builder instance.
* @param \Illuminate\Database\Eloquent\Builder|null $builder
* @throws \Kettasoft\Filterable\Exceptions\MissingBuilderException
*/
private function initQueryBuilderInstance(Builder|null $builder = null)
{
if ($builder)
return $builder;
if (isset($this->builder))
return $this->builder;
if ($this->model instanceof Model) {
return $this->model->query();
}
if (is_a($this->model, Model::class, true)) {
return $this->model::query();
}
throw new MissingBuilderException;
}
/**
* Set model.
* @param \Illuminate\Database\Eloquent\Model|string $model
* @return static
*/
public function setModel(Model|string $model): static
{
$this->model = $model;
return $this;
}
/**
* Get model.
* @return Model|string
*/
public function getModel()
{
return $this->model;
}
/**
* Get model instance object.
* @return Model|object|null
*/
public function getModelInstance()
{
if ($this->model instanceof Model) {
return $this->model;
}
if (is_a($this->model, Model::class, true)) {
return new $this->model;
}
return null;
}
/**
* Create new Filterable instance.
* @param \Illuminate\Http\Request|null $request
* @return static
*/
public static function create(Request|null $request = null): static
{
return new static($request ?? App::make(Request::class));
}
/**
* Apply a callback conditionally and return a new modified instance.
* @param bool $condition
* @param callable(static): void $callback
* @return static
* @link https://kettasoft.github.io/filterable/features/conditional-logic
*/
public function when(bool $condition, callable $callback)
{
if ($condition) {
call_user_func($callback, $this);
}
return $this;
}
/**
* Inverse of `when` method.
* @param bool $condition
* @param callable(static): void $callback
* @return static
* @link https://kettasoft.github.io/filterable/features/conditional-logic
*/
public function unless(bool $condition, callable $callback)
{
return $this->when(!$condition, $callback);
}
/**
* Allow the query to pass through a custom pipeline of pipes (callables).
*
* @param array<callable(\Illuminate\Database\Eloquent\Builder, static): \Illuminate\Database\Eloquent\Builder> $pipes
* @return static
* @link https://kettasoft.github.io/filterable/features/through
*/
public function through(array $pipes): static
{
foreach ($pipes as $pipe) {
if (!is_callable($pipe)) {
throw new \InvalidArgumentException('All pipes passed to `through` must be callable.');
}
$pipe($this->builder, $this);
}
return $this;
}
/**
* Override the default engine for this filterable instance.
* @param \Kettasoft\Filterable\Engines\Foundation\Engine|string $engine
* @return Filterable
*/
public function useEngine(Engine|string $engine): static
{
$this->engine = EngineManager::generate($engine, $this);
return $this;
}
/**
* Get current engine.
* @return Engine
*/
public function getEngine(): Engine
{
return $this->engine;
}
/**
* Get the current request instance.
* @return Request
*/
public function getRequest(): Request
{
return $this->request;
}
/**
* Get sanitizer instance.
* @return Sanitizer
*/
public function getSanitizerInstance(): Sanitizer
{
return $this->sanitizer;
}
/**
* Set manual data injection.
* @param array $data
* @param bool $override
* @return static
*/
public function setData(array $data, bool $override = true): static
{
$this->data = $override ? $data : array_merge($this->data, $data);
return $this;
}
/**
* Create new Filterable instance with custom Request.
* @param \Illuminate\Http\Request $request
* @return static
*/
public static function withRequest(Request $request): static
{
return static::create($request);
}
/**
* Set a new sanitizers classes.
* @param array $sanitizers
* @return Filterable
*/
public function setSanitizers(array $sanitizers, bool $override = true): static
{
$this->sanitizers = $override ? $sanitizers : array_merge($this->sanitizers, $sanitizers);
$this->sanitizer->setSanitizers($this->sanitizers);
return $this;
}
/**
* Disable running sanitizers on the filters.
* @return static
*/
public function withoutSanitizers(): static
{
$this->sanitizers = [];
$this->sanitizer->setSanitizers([]);
return $this;
}
/**
* Parse incomming data from request.
* @return void
*/
private function parseIncomingRequestData()
{
$this->data = [...$this->request->all(), ...$this->request->json()->all()];
}
/**
* Get current data.
* @return array
*/
public function getData(): mixed
{
return $this->filterKey === null ? $this->data : $this->data[$this->filterKey] ?? $this->data;
}
/**
* Fetch all relevant filters from the filter API class.
*
* @return array
*/
public function getFilterAttributes(): array
{
return property_exists($this, 'filters')
&& is_array($this->filters) ? $this->filters : [];
}
/**
* Resolve default engine to Filterable instance.
* @return void
*/
private function resolveEngine()
{
$this->useEngine((new HeaderDrivenEngineSelector($this->request))->resolve());
}
/**
* Set request source.
* @param string $source
* @throws \Kettasoft\Filterable\Exceptions\RequestSourceIsNotSupportedException
* @return static
*/
public function setSource(string $source)
{
if (!in_array($source, ['query', 'input', 'json'])) {
throw new RequestSourceIsNotSupportedException($source);
}
$this->requestSource = $source;
return $this;
}
/**
* Ignore empty or null values.
* @return Filterable
*/
public function ignoreEmptyValues(): static
{
$this->ignoreEmptyValues = true;
return $this;
}
/**
* Check if current filterable class has ignored empty values.
* @return bool
*/
public function hasIgnoredEmptyValues(): bool
{
return $this->ignoreEmptyValues === true;
}
/**
* Enable Header-driven mode per request.
* @param mixed $config
* @return Filterable
*/
public function withHeaderDrivenMode($config = []): static
{
return $this->useEngine((new HeaderDrivenEngineSelector($this->request, array_merge(
config('filterable.header_driven_mode', []),
['enabled' => true],
$config
)))->resolve());
}
/**
* Get allowed fields to apply filtering.
* @return array
*/
public function getAllowedFields(): array
{
return $this->allowedFields;
}
/**
* List of supported SQL operators you want to allow when parsing the expressions.
* @return array
*/
public function getAllowedOperators(): array
{
return $this->allowedOperators;
}
/**
* Set allowed operators and override global operators.
* @param array $operators
* @return static
*/
public function allowedOperators(array $operators): static
{
$this->allowedOperators = $operators;
return $this;
}
/**
* Define allowed fields to filtering.
* @param array $fields
* @return Filterable
*/
public function setAllowedFields(array $fields, bool $override = false): static
{
$this->allowedFields = $override ? $fields : array_merge($this->allowedFields, $fields);
$this->resources->fields->fill($this->allowedFields);
return $this;
}
/**
* Enable strict mode in this instance.
* @return Filterable
*/
public function strict(): static
{
$this->strict = true;
return $this;
}
/**
* Enable strict mode in this instance.
* @return Filterable
*/
public function permissive(): static
{
$this->strict = false;
return $this;
}
/**
* Check if filter has strict mode.
* @return mixed
*/
public function isStrict()
{
if (is_bool($this->strict)) {
return $this->strict;
}
return null;
}
/**
* Get columns wrapper.
* @return array
*/
public function getFieldsMap(): array
{
return $this->fieldsMap;
}
/**
* Set fields wrapper.
* @param array $fields
* @param bool $override
* @return static
*/
public function setFieldsMap($fields, bool $override = true): static
{
$this->fieldsMap = $override ? $fields : array_merge($this->fieldsMap, $fields);
return $this;
}
/**
* Get registered filter builder.
* @return Builder
*/
public function getBuilder(): Builder
{
return $this->builder;
}
/**
* Set a new builder.
* @param Builder $builder
* @return static
*/
public function setBuilder(Builder $builder): static
{
$this->builder = $builder;
return $this;
}
/**
* Auto-detect filterable fields from model fillable attributes.
* @param bool $override To override current fields
* @return static
*/
public function autoSetAllowedFieldsFromModel(bool $override = false): static
{
$fillable = $this->builder->getModel()->getFillable();
$this->allowedFields = $override ? $fillable : array_merge($this->allowedFields, $fillable);
return $this;
}
/**
* Get the SQL representation of the filtered query.
* @param \Illuminate\Database\Eloquent\Builder|null $builder
* @param mixed $withBindings
* @return string
*/
public function toSql(Builder|null $builder = null, $withBindings = false): string
{
$builder = $this->apply($builder ?? $this->builder);
return $withBindings ? $builder->toRawSql() : $builder->toSql();
}
/**
* Retrieve an input item from the request.
* @param string $key
* @return mixed
*/
public function get(string $key)
{
if (!in_array($source = $this->requestSource ?? config('filterable.request_source', 'query'), ['query', 'input', 'json'])) {
throw new RequestSourceIsNotSupportedException($source);
}
return $this->request->{$source}($key);
}
/**
* Dynamically retrieve attributes from the request.
* @param mixed $property
* @return mixed
*/
public function __get($property): mixed
{
if (property_exists($this, $property)) {
return $this->{$property};
}
return $this->get($property);
}
}