-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathHasApiModelBehavior.php
More file actions
1394 lines (1190 loc) · 48.4 KB
/
HasApiModelBehavior.php
File metadata and controls
1394 lines (1190 loc) · 48.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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Fleetbase\Traits;
use Fleetbase\Support\ApiModelCache;
use Fleetbase\Support\Auth;
use Fleetbase\Support\Http;
use Fleetbase\Support\QueryOptimizer;
use Fleetbase\Support\Resolve;
use Fleetbase\Support\Utils;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
/**
* Adds API Model Behavior.
*/
trait HasApiModelBehavior
{
/**
* Boot the HasApiModelBehavior trait.
*
* Registers model event listeners for automatic cache invalidation.
*/
public static function bootHasApiModelBehavior()
{
// Only set up cache invalidation if caching is enabled
if (!config('api.cache.enabled', true)) {
return;
}
// Invalidate cache when model is created
static::created(function ($model) {
$model->invalidateApiCacheOnChange();
});
// Invalidate cache when model is updated
static::updated(function ($model) {
$model->invalidateApiCacheOnChange();
});
// Invalidate cache when model is deleted
static::deleted(function ($model) {
$model->invalidateApiCacheOnChange();
});
// Invalidate cache when model is restored (soft deletes)
if (method_exists(static::class, 'restored')) {
static::restored(function ($model) {
$model->invalidateApiCacheOnChange();
});
}
}
/**
* Invalidate API cache when model changes.
*/
protected function invalidateApiCacheOnChange(): void
{
if (!config('api.cache.enabled', true)) {
return;
}
// Get company UUID if available
$companyUuid = session('company', $this->company_uuid);
// Use ApiModelCache if available
ApiModelCache::invalidateModelCache($this, $companyUuid);
ApiModelCache::invalidateModelCache(new self(), $companyUuid);
}
/**
* The name of the database column used to store the public ID for this model.
*
* @var string
*/
public static $publicIdColumn = 'public_id';
/**
* Get the fully qualified name of the database column used to store the public ID for this model.
*
* @return string the fully qualified name of the public ID column
*/
public function getQualifiedPublicId()
{
return static::$publicIdColumn;
}
/**
* Get the plural name of this model, either from the `pluralName` property or by inflecting the table name.
*
* @return string the plural name of this model
*/
public function getPluralName(): string
{
if (isset($this->pluralName)) {
return $this->pluralName;
}
if (isset($this->payloadKey)) {
return Str::plural($this->payloadKey);
}
return Str::plural($this->getTable());
}
/**
* Get the singular name of this model, either from the `singularName` property or by inflecting the table name.
*
* @return string the singular name of this model
*/
public function getSingularName(): string
{
if (isset($this->singularName)) {
return $this->singularName;
}
if (isset($this->payloadKey)) {
return Str::singular($this->payloadKey);
}
return Str::singular($this->getTable());
}
/**
* Returns a list of fields that can be searched / filtered by. This includes
* all fillable columns, the primary key column, and the created_at
* and updated_at columns.
*
* @return array
*/
public function searcheableFields()
{
if ($this->searchableColumns) {
return $this->searchableColumns;
}
return array_merge(
$this->fillable,
[
$this->getKeyName(),
$this->getCreatedAtColumn(),
$this->getUpdatedAtColumn(),
]
);
}
/**
* Retrieves all records based on request data passed in.
*
* @param Request $request the HTTP request containing the input data
* @param \Closure|null $queryCallback optional callback to modify data with Request and QueryBuilder instance
*
* @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Contracts\Pagination\LengthAwarePaginator
*/
public function queryFromRequest(Request $request, ?\Closure $queryCallback = null)
{
// Check if model has caching enabled via HasApiModelCache trait
if ($this->shouldUseCache()) {
return $this->queryFromRequestCached($request, $queryCallback);
}
$columns = $request->input('columns', ['*']);
$limit = $request->integer('limit', 30);
$offset = $request->integer('offset', 0);
$page = max(1, $request->integer('page', 1));
$calculateOffset = $request->missing('offset') && $request->has('page');
// Clamp limit
if ($limit !== -1) {
$limit = max(1, min($limit, 100));
}
/**
* @var \Illuminate\Database\Eloquent\Builder $builder
*/
$builder = $this->searchBuilder($request, $columns);
// Auto-calculate offset from page
if ($calculateOffset) {
$offset = ($page - 1) * $limit;
}
// Handle limit
if ($limit === -1) {
$builder->limit(PHP_INT_MAX);
} elseif ($limit > 0) {
$builder->limit($limit);
}
// Handle offset
if ($offset > 0) {
$builder->offset($offset);
}
// if queryCallback is supplied
if (is_callable($queryCallback)) {
$queryCallback($builder, $request);
}
/* debug */
// Utils::sqlDump($builder);
if (Http::isInternalRequest($request)) {
return $builder->fastPaginate($limit, $columns);
}
// get the results
$result = $builder->get($columns);
// mutate if mutation causing params present
return static::mutateModelWithRequest($request, $result);
}
/**
* Check if this model should use caching.
*/
protected function shouldUseCache(): bool
{
// Check if HasApiModelCache trait is used
$traits = class_uses_recursive(static::class);
$hasCacheTrait = isset($traits['Fleetbase\\Traits\\HasApiModelCache']);
if (!$hasCacheTrait) {
return false;
}
// Check if caching is disabled for this specific model
// Use isset() to detect both declared properties and dynamically set properties
if (isset($this->disableApiCache) && $this->disableApiCache === true) {
return false;
}
// Check if API caching is enabled globally
return config('api.cache.enabled', true);
}
/**
* Static alias for queryFromRequest().
*
* @see queryFromRequest()
*
* @param Request $request the HTTP request containing the input data
* @param \Closure|null $queryCallback optional callback to modify data with Request and QueryBuilder instance
* @param bool $withoutCache whether to bypass the cache for this query
*
* @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Contracts\Pagination\LengthAwarePaginator
*
* @static
*
* @example
* ```php
* // Query with cache disabled using parameter
* $results = Place::queryWithRequest($request, function (&$query) {
* $query->where('owner_uuid', $customer->uuid);
* }, withoutCache: true);
* ```
*/
public static function queryWithRequest(Request $request, ?\Closure $queryCallback = null, bool $withoutCache = false)
{
$instance = new static();
if ($withoutCache) {
$instance->disableApiCache = true;
}
return $instance->queryFromRequest($request, $queryCallback);
}
/**
* Disable caching for the next query.
*
* This method creates a new instance with caching disabled for that specific instance.
* Safe for use in Laravel Octane and concurrent request environments.
*
* @example
* ```php
* // Query without cache - use queryFromRequest (not queryWithRequest)
* $results = Place::withoutCache()->queryFromRequest($request, function (&$query) {
* $query->where('owner_uuid', $customer->uuid);
* });
* ```
*/
public static function withoutCache(): static
{
$instance = new static();
$instance->disableApiCache = true;
return $instance;
}
/**
* Create a new record in the database based on the input data in the given request.
*
* @param Request $request the HTTP request containing the input data
* @param callable|null $onBefore an optional callback function to execute before creating the record
* @param callable|null $onAfter an optional callback function to execute after creating the record
* @param array $options an optional array of additional options
*
* @return mixed the newly created record, or a JSON response if the callbacks return one
*/
public function createRecordFromRequest($request, ?callable $onBefore = null, ?callable $onAfter = null, array $options = [])
{
$input = $this->getApiPayloadFromRequest($request);
$input = $this->fillSessionAttributes($input);
if (is_callable($onBefore)) {
$before = $onBefore($request, $input);
if ($before instanceof JsonResponse) {
return $before;
}
}
// Check if the Model has a custom creation method defined
if (property_exists($this, 'creationMethod') && method_exists($this, $this->creationMethod)) {
// Call the custom creation method
$record = $this->{$this->creationMethod}($input);
} else {
// Default creation method
$record = static::create($input);
}
if (isset($options['return_object']) && $options['return_object'] === true) {
return $record;
}
if (is_callable($onAfter)) {
$after = $onAfter($request, $record, $input);
if ($after instanceof JsonResponse) {
return $after;
}
}
$record->refresh();
// PERFORMANCE OPTIMIZATION: Use load() instead of re-querying the database
// This avoids an unnecessary second database query
$with = $request->or(['with', 'expand'], []);
if (!empty($with)) {
$record->load($with);
}
// Load counts if requested
$withCount = $request->array('with_count', []);
if (!empty($withCount)) {
$record->loadCount($withCount);
}
return static::mutateModelWithRequest($request, $record);
}
/**
* Update an existing record in the database based on the input data in the given request.
*
* @param Request $request the HTTP request containing the input data
* @param mixed $id the ID of the record to update
* @param callable|null $onBefore an optional callback function to execute before updating the record
* @param callable|null $onAfter an optional callback function to execute after updating the record
* @param array $options an optional array of additional options
*
* @return mixed the updated record, or a JSON response if the callbacks return one
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the record with the given ID is not found
* @throws \Exception if the input contains an invalid parameter that is not fillable
*/
public function updateRecordFromRequest(Request $request, $id, ?callable $onBefore = null, ?callable $onAfter = null, array $options = [])
{
$builder = $this->where(function ($q) use ($id) {
$publicIdColumn = $this->getQualifiedPublicId();
$q->where($this->getQualifiedKeyName(), $id);
if ($this->isColumn($publicIdColumn)) {
$q->orWhere($publicIdColumn, $id);
}
});
// Defence-in-depth: scope update to the caller's company to prevent
// cross-tenant modification (GHSA-3wj9-hh56-7fw7).
$companyUuid = session('company');
if ($companyUuid && $this->isColumn($this->qualifyColumn('company_uuid'))) {
$builder->where($this->qualifyColumn('company_uuid'), $companyUuid);
}
$builder = $this->applyDirectivesToQuery($request, $builder);
$record = $builder->first();
if (!$record) {
throw new \Exception($this->getApiHumanReadableName() . ' not found');
}
$input = $this->getApiPayloadFromRequest($request);
$input = $this->fillSessionAttributes($input, [], ['updated_by_uuid']);
if (is_callable($onBefore)) {
$before = $onBefore($request, $record, $input);
if ($before instanceof JsonResponse) {
return $before;
}
}
$keys = array_keys($input);
foreach ($keys as $key) {
if ($this->isInvalidUpdateParam($key)) {
throw new \Exception('Invalid param "' . $key . '" in update request!');
}
}
// Remove ID's and timestamps from input
$input = Arr::except($input, ['uuid', 'public_id', 'deleted_at', 'updated_at', 'created_at']);
try {
$record->update($input);
} catch (\Exception $e) {
throw new \Exception(app()->hasDebugModeEnabled() ? $e->getMessage() : 'Failed to update ' . $this->getApiHumanReadableName());
}
if (isset($options['return_object']) && $options['return_object'] === true) {
return $record;
}
if (is_callable($onAfter)) {
$after = $onAfter($request, $record, $input);
if ($after instanceof JsonResponse) {
return $after;
}
}
$record->refresh();
// PERFORMANCE OPTIMIZATION: Use load() instead of re-querying the database
// This avoids an unnecessary second database query
$with = $request->or(['with', 'expand'], []);
if (!empty($with)) {
$record->load($with);
}
// Load counts if requested
$withCount = $request->array('with_count', []);
if (!empty($withCount)) {
$record->loadCount($withCount);
}
return static::mutateModelWithRequest($request, $record);
}
/**
* Removes a record from the database based on the given ID.
*
* @param mixed $id The ID or public ID of the record to remove
*
* @return bool|int The number of records affected, or false if the record is not found
*
* @throws \Exception If there's an issue while deleting the record
*/
public function remove($id)
{
$record = $this->where(function ($q) use ($id) {
$publicIdColumn = $this->getQualifiedPublicId();
$q->where($this->getQualifiedKeyName(), $id);
if ($this->isColumn($publicIdColumn)) {
$q->orWhere($publicIdColumn, $id);
}
});
if (!$record) {
return false;
}
try {
return $record->delete();
} catch (\Exception $e) {
throw $e;
}
}
/**
* Removes multiple records from the database based on the given IDs.
*
* @param array $ids The array of IDs or public IDs of the records to remove
*
* @return bool|int The number of records affected, or false if no records are found
*
* @throws \Exception If there's an issue while deleting the records
*/
public function bulkRemove($ids = [])
{
$records = $this->where(function ($q) use ($ids) {
$publicIdColumn = $this->getQualifiedPublicId();
$q->whereIn($this->getQualifiedKeyName(), $ids);
if ($this->isColumn($publicIdColumn)) {
$q->orWhereIn($publicIdColumn, $ids);
}
});
// Defence-in-depth: scope bulk delete to the caller's company to prevent
// cross-tenant deletion (GHSA-3wj9-hh56-7fw7).
$companyUuid = session('company');
if ($companyUuid && $this->isColumn($this->qualifyColumn('company_uuid'))) {
$records->where($this->qualifyColumn('company_uuid'), $companyUuid);
}
if (!$records) {
return false;
}
$count = $records->count();
try {
$records->delete();
$this->invalidateApiCacheOnChange();
return $count;
} catch (\Exception $e) {
throw $e;
}
}
/**
* Mutates the given model, collection or array of results with the request.
* Applies 'with' and 'without' parameters to the result.
*
* @param Request $request The request object containing the 'with' and 'without' parameters
* @param mixed $result The model, collection or array of results to be mutated
*
* @return mixed The mutated model, collection or array of results
*/
public static function mutateModelWithRequest(Request $request, $result)
{
$with = $request->or(['with', 'expand'], []);
$without = $request->array('without');
// handle collection or array of results
if (is_array($result) || $result instanceof \Illuminate\Support\Collection) {
return collect($result)->map(
function ($model) use ($request) {
return static::mutateModelWithRequest($request, $model);
}
);
}
if ($with) {
$result->load($with);
}
if ($without) {
$result->setHidden($without);
}
return $result;
}
/**
* Fills the target array with session attributes based on the specified rules.
* Allows to apply exceptions and only specific attributes to be filled.
*
* @param array $target The target array to fill with session attributes
* @param array $except The list of attributes that should not be filled (default: [])
* @param array $only The list of attributes that should only be filled (default: [])
*
* @return array The filled target array with session attributes
*/
public function fillSessionAttributes(?array $target = [], array $except = [], array $only = []): array
{
$fill = [];
$attributes = [
'user_uuid' => 'user',
'author_uuid' => 'user',
'uploader_uuid' => 'user',
'creator_uuid' => 'user',
'created_by_uuid' => 'user',
'updated_by_uuid' => 'user',
'company_uuid' => 'company',
];
foreach ($attributes as $attr => $key) {
if ((!empty($only) && !in_array($attr, $only)) || isset($target[$attr])) {
continue;
}
if ($this->isSessionAgnosticColumn($attr)) {
continue;
}
if ($this->isFillable($attr) && !in_array($except, array_keys($attributes))) {
$fill[$attr] = session($key);
}
}
return array_merge($target, $fill);
}
/**
* Checks if request contains relationships.
*
* @param \Illuminate\Database\Query\Builder $builder
*
* @return \Illuminate\Database\Query\Builder
*/
public function withRelationships(Request $request, $builder)
{
$with = $request->or(['with', 'expand']);
$without = $request->array('without', []);
if (!$with && !$without) {
return $builder;
}
$contains = is_array($with) ? $with : explode(',', $with);
foreach ($contains as $contain) {
$camelVersion = Str::camel(trim($contain));
if (\method_exists($this, $camelVersion)) {
$builder->with($camelVersion);
continue;
}
$snakeCase = Str::snake(trim($contain));
if (\method_exists($this, $snakeCase)) {
$builder->with(trim($snakeCase));
continue;
}
if (strpos($contain, '.') !== false) {
$parts = array_map(
function ($part) {
return Str::camel($part);
},
explode('.', $contain)
);
$contain = implode('.', $parts);
$builder->with($contain);
continue;
}
}
if ($without) {
$builder->without($without);
}
return $builder;
}
/**
* Checks if request includes counts.
*
* @param Request $request
* @param \Illuminate\Database\Query\Builder $builder
*
* @return \Illuminate\Database\Query\Builder
*/
public function withCounts($request, $builder)
{
$count = $request->or(['count', 'with_count']);
if (!$count) {
return $builder;
}
$counters = explode(',', $count);
foreach ($counters as $counter) {
if (\method_exists($this, $counter)) {
$builder->withCount($counter);
continue;
}
$camelVersion = Str::camel($counter);
if (\method_exists($this, $camelVersion)) {
$builder->withCount($camelVersion);
continue;
}
}
return $builder;
}
/**
* Apply sorts to query.
*
* @param Request $request - HTTP Request
* @param \Illuminate\Database\Query\Builder $builder - Query Builder
*
* @return \Illuminate\Database\Query\Builder
*/
public function applySorts($request, $builder)
{
// Grab the raw sort input
$sorts = (array) $request->array('sort');
// Nothing to sort by
if (empty($sorts)) {
return $builder;
}
foreach ($sorts as $sort) {
$sort = trim($sort);
if ($sort === '') {
continue;
}
// Handle special keywords that don't care about column name
if (Schema::hasColumn($this->getTable(), $this->getCreatedAtColumn())) {
$sortLower = strtolower($sort);
if ($sortLower === 'latest') {
$builder->orderBy($this->qualifySortColumn($this->getCreatedAtColumn()), 'desc');
continue;
}
if ($sortLower === 'oldest') {
$builder->orderBy($this->qualifySortColumn($this->getCreatedAtColumn()), 'asc');
continue;
}
}
// Custom distance sort hook
if (strtolower($sort) === 'distance') {
$builder->orderByDistance();
continue;
}
// Normal case: "status", "-status", "status:desc", etc.
// Delegate parsing of direction & column to Http::useSort
[$column, $direction] = Http::useSort($sort);
if (!empty($column)) {
$builder->orderBy($this->qualifySortColumn($column), $direction ?: 'asc');
}
}
return $builder;
}
/**
* Retrieves a record based on primary key id.
*
* The query is automatically scoped to the current company via the
* CompanyScope global scope registered on the base Model. This method
* adds an explicit defence-in-depth company_uuid check as well so that
* the constraint is visible at the call-site and survives any future
* withoutGlobalScope() calls higher up the stack.
*
* @param string $id - The ID
* @param Request $request - HTTP Request
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function getById($id, ?callable $queryCallback = null, Request $request)
{
$builder = $this->where(function ($q) use ($id) {
$publicIdColumn = $this->getQualifiedPublicId();
$q->where($this->getQualifiedKeyName(), $id);
if ($this->isColumn($publicIdColumn)) {
$q->orWhere($publicIdColumn, $id);
}
});
// Defence-in-depth: explicitly scope to the caller's company when the
// model has a company_uuid column and a session company is available.
// The CompanyScope global scope provides the primary protection; this
// explicit clause ensures the constraint survives withoutGlobalScope().
$companyUuid = session('company');
if ($companyUuid && $this->isColumn($this->qualifyColumn('company_uuid'))) {
$builder->where($this->qualifyColumn('company_uuid'), $companyUuid);
}
if (is_callable($queryCallback)) {
$queryCallback($builder, $request);
}
$builder = $this->withCounts($request, $builder);
$builder = $this->withRelationships($request, $builder);
$builder = $this->applySorts($request, $builder);
$builder = $this->applyDirectivesToQuery($request, $builder);
return $builder->first();
}
/**
* Retrieves the options for the given model.
*
* @return array An array of options with 'value' and 'label' keys
*/
public function getOptions()
{
$builder = $this->select($this->option_key, $this->option_label)
->orderBy($this->option_label, 'asc')
->get();
// convert data to standard object {value:'', label:''}
$arr = [];
foreach ($builder as $x) {
if ($x[$this->option_label]) {
$arr[] = [
'value' => $x[$this->option_key],
'label' => $x[$this->option_label],
];
}
}
return $arr;
}
/**
* Searches for records based on the request parameters and returns a paginated result.
*
* @param Request $request The request object containing the search parameters
*
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator The paginated search results
*/
public function searchRecordFromRequest(Request $request)
{
$limit = $request->integer('limit', 30);
$builder = $this->searchBuilder($request);
return $builder->fastPaginate($limit);
}
/**
* Builds the search query based on the request parameters.
*
* @param Request $request The request object containing the search parameters
*
* @return \Illuminate\Database\Eloquent\Builder The search query builder
*/
public function searchBuilder(Request $request, $columns = ['*'])
{
$builder = self::query()->select($columns);
// PERFORMANCE OPTIMIZATION: Apply authorization directives FIRST to reduce dataset early
$builder = $this->applyDirectivesToQuery($request, $builder);
// CRITICAL: Apply custom filters ALWAYS (handles queryForInternal/queryForPublic)
// This MUST run before the fast path check to ensure data isolation
$builder = $this->applyCustomFilters($request, $builder);
// PERFORMANCE OPTIMIZATION: Check if this is a simple query (no filters, sorts, or relationships)
// This avoids unnecessary method calls for the most common case
$hasFilters = $request->has('filters') || count($request->except(['limit', 'offset', 'page', 'sort', 'order'])) > 0;
$hasSorts = $request->has('sort') || $request->has('order');
$hasRelationships = $request->has('with') || $request->has('expand') || $request->has('without');
$hasCounts = $request->has('with_count');
if (!$hasFilters && !$hasSorts && !$hasRelationships && !$hasCounts) {
// Fast path: no additional processing needed (custom filters already applied)
return $builder;
}
// PERFORMANCE OPTIMIZATION: Only apply optimized filters if there are actual filter parameters
if ($hasFilters) {
$builder = $this->applyOptimizedFilters($request, $builder);
}
// Only apply sorts if requested
if ($hasSorts) {
$builder = $this->applySorts($request, $builder);
}
// Only eager-load relationships if requested
if ($hasRelationships) {
$builder = $this->withRelationships($request, $builder);
}
if ($hasCounts) {
$builder = $this->withCounts($request, $builder);
}
return $builder;
}
/**
* Applies all authorization directives from the request to the given query builder.
*
* This method retrieves directives from the request using the `Auth::getDirectivesFromRequest` method,
* then iterates over each directive and applies it to the provided query builder. The directives modify
* the query to enforce the appropriate access controls based on the authenticated user's permissions.
*
* @param Request $request the HTTP request containing the authorization directives
* @param \Illuminate\Database\Eloquent\Builder $builder the query builder instance to which the directives will be applied
*
* @return \Illuminate\Database\Eloquent\Builder the modified query builder with all directives applied
*/
public function applyDirectivesToQuery(Request $request, $builder)
{
$directives = Auth::getDirectivesFromRequest($request);
$uniqueDirectives = $directives->unique('rules');
foreach ($uniqueDirectives as $directive) {
$directive->apply($builder);
}
return $builder;
}
/**
* Optimizes the given query builder by removing duplicate where clauses.
*
* This method takes a query builder instance and passes it to the QueryOptimizer,
* which processes the query to remove any duplicate where clauses while ensuring
* that the associated bindings are correctly managed. This optimization helps in
* improving query performance and avoiding potential issues with redundant conditions.
*
* @param \Illuminate\Database\Eloquent\Builder $builder the query builder instance to optimize
*
* @return \Illuminate\Database\Eloquent\Builder the optimized query builder with unique where clauses
*/
public function optimizeQuery($builder)
{
return QueryOptimizer::removeDuplicateWheres($builder);
}
/**
* Applies custom filters to the search query based on the request parameters.
*
* @param Request $request The request object containing the custom filter parameters
* @param \Illuminate\Database\Eloquent\Builder $builder The search query builder
*
* @return \Illuminate\Database\Eloquent\Builder The search query builder with custom filters applied
*/
public function applyCustomFilters(Request $request, $builder)
{
$resourceFilter = Resolve::httpFilterForModel($this, $request);
if ($resourceFilter) {
$builder->filter($resourceFilter);
}
// handle with/without here
$with = $request->or(['with', 'expand'], []);
$without = $request->array('without');
$withoutRelations = $request->boolean('without_relations');
// camelcase all params in with and apply
if (is_array($with)) {
$with = array_map(
function ($relationship) {
return Str::camel($relationship);
},
$with
);
$builder = $builder->with($with);
}
// camelcase all params in with and apply
if (is_array($without)) {
$without = array_map(
function ($relationship) {
return Str::camel($relationship);
},
$without
);
$builder = $builder->without($without);
}
// if to query without all relations
if ($withoutRelations) {
$builder = $builder->withoutRelations();
}
return $builder;
}
/**
* Applies filters to the search query based on the request parameters.
*
* @param Request $request The request object containing the filter parameters
* @param \Illuminate\Database\Eloquent\Builder $builder The search query builder
*
* @return \Illuminate\Database\Eloquent\Builder The search query builder with filters applied
*/
public function applyFilters(Request $request, $builder)
{
$operators = $this->getQueryOperators();
$filters = $request->input('filters', []);
foreach ($filters as $column => $values) {
if (!in_array($column, $this->searcheableFields())) {
continue;
}
$valueParts = explode(':', $values);
$operator = 'eq';
$operator_symbol = '=';
$value = null;
if (count($valueParts) > 1) {
$operator = $valueParts[0];
$operator_symbol = $operators[$operator] ?? '=';
$value = $valueParts[1];
} else {
$value = $valueParts[0];
}