-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathAttributes.php
87 lines (76 loc) · 2.05 KB
/
Attributes.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
<?php
declare(strict_types=1);
namespace TiMacDonald\JsonApi\Concerns;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\PotentiallyMissing;
use Illuminate\Support\Collection;
use TiMacDonald\JsonApi\Support\Fields;
trait Attributes
{
/**
* @internal
*/
private static bool $minimalAttributes = false;
/**
* @api
*
* @param (callable(): void)|null $callback
* @return void
*/
public static function minimalAttributes(callable|null $callback = null)
{
self::$minimalAttributes = true;
if ($callback === null) {
return;
}
try {
$callback();
} finally {
self::$minimalAttributes = false;
}
}
/**
* @api
* @infection-ignore-all
*
* @return void
*/
public static function maximalAttributes()
{
self::$minimalAttributes = false;
}
/**
* @internal
*
* @return Collection<string, mixed>
*/
private function requestedAttributes(Request $request)
{
return Collection::make($this->resolveAttributes($request))
->only($this->requestedFields($request))
->map(fn (mixed $value): mixed => value($value))
->reject(fn (mixed $value): bool => $value instanceof PotentiallyMissing && $value->isMissing());
}
/**
* @internal
*
* @return Collection<string, mixed>
*/
private function resolveAttributes(Request $request)
{
return Collection::make(property_exists($this, 'attributes') ? $this->attributes : [])
->mapWithKeys(fn (string $attribute, int|string $key): array => [
$attribute => fn () => $this->resource->{$attribute},
])
->merge($this->toAttributes($request));
}
/**
* @internal
*
* @return array<int, string>|null
*/
private function requestedFields(Request $request)
{
return Fields::getInstance()->parse($request, $this->toType($request), self::$minimalAttributes);
}
}