Skip to content

Commit 2862fc0

Browse files
committed
fix: improve type hints and simplify data filtering in Filters.php
1 parent c683259 commit 2862fc0

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

src/Filters/Filters.php

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22

33
namespace Ark4ne\JsonApi\Filters;
44

5+
use Ark4ne\JsonApi\Support\Values;
56
use Closure;
67
use Illuminate\Contracts\Auth\Access\Gate;
78
use Illuminate\Http\Request;
89
use Illuminate\Http\Resources\MissingValue;
10+
use Illuminate\Http\Resources\PotentiallyMissing;
911
use Illuminate\Support\Collection;
1012

1113
/**
@@ -34,7 +36,7 @@ public function can(iterable|string $abilities, array $arguments = [], string $g
3436
/**
3537
* Add a custom filter rule
3638
*
37-
* @param Closure $callback Callback that receives (Request $request, Model $model) and returns bool
39+
* @param Closure(Request, Resource): bool $callback Callback that receives (Request $request, Model $model) and returns bool
3840
* @return static
3941
*/
4042
public function when(Closure $callback): static
@@ -46,40 +48,43 @@ public function when(Closure $callback): static
4648
/**
4749
* Apply all filters to the given data
4850
*
49-
* @param mixed $data
51+
* @param Request $request
52+
* @param null|PotentiallyMissing|Resource|iterable<array-key, Resource> $data
5053
* @return mixed
5154
*/
5255
public function apply(Request $request, mixed $data): mixed
5356
{
54-
if ($data instanceof MissingValue || $data === null) {
57+
if ($data === null) {
58+
return $data;
59+
}
60+
if (Values::isMissing($data)) {
5561
return $data;
5662
}
5763

5864
// If it's a collection/array, filter each item
5965
if (is_iterable($data)) {
60-
$filtered = [];
61-
foreach ($data as $key => $item) {
62-
if ($this->shouldInclude($request, $item)) {
63-
$filtered[$key] = $item;
64-
}
65-
}
66-
66+
$filtered = (new Collection($data))
67+
->filter(fn($item) => $this->shouldInclude($request, $item));
68+
6769
// Preserve the original collection type
6870
if ($data instanceof Collection) {
69-
return new Collection($filtered);
71+
return $filtered;
7072
}
7173

72-
return $filtered;
74+
return $filtered->all();
7375
}
7476

7577
// Single model - check if it should be included
76-
return $this->shouldInclude($request, $data) ? $data : new MissingValue();
78+
return $this->shouldInclude($request, $data)
79+
? $data
80+
: new MissingValue();
7781
}
7882

7983
/**
8084
* Check if a model should be included based on all filter rules
8185
*
82-
* @param mixed $model
86+
* @param Request $request
87+
* @param Resource $model
8388
* @return bool
8489
*/
8590
protected function shouldInclude(Request $request, mixed $model): bool

0 commit comments

Comments
 (0)