-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResource.php
More file actions
354 lines (298 loc) · 8.83 KB
/
Copy pathResource.php
File metadata and controls
354 lines (298 loc) · 8.83 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
<?php
declare(strict_types = 1);
namespace BlueBeetle\ApiToolkit\Resources;
use BadMethodCallException;
use BlueBeetle\ApiToolkit\Parsers\FieldParser;
use BlueBeetle\ApiToolkit\Parsers\Filters\Filter;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use RuntimeException;
/**
* @template TModel
*
* Child classes should implement the following methods with their own type hints:
*
* - attributes(MyModel $model): array (required)
* - self(MyModel $model): string|null (optional)
* - links(MyModel $model): array (optional)
* - meta(MyModel $model): array (optional)
*/
class Resource
{
/**
* @var (Closure(mixed, Request|null): string)|null
*/
private static Closure | null $idResolver = null;
/**
* @var (Closure(mixed, Request|null): string)|null
*/
private static Closure | null $typeResolver = null;
/**
* The model class this resource represents.
* When set to an Eloquent model, the JSON:API type is derived from its table name.
*
* @var class-string<TModel>
*/
protected string $model = '';
/**
* Override the JSON:API type. When empty, derived from the model's table name.
*/
protected string $type = '';
/**
* The current request instance, available in all methods via $this->request.
*/
protected Request | null $request = null;
/**
* Cached parsed sparse fieldsets for the current request.
*
* @var array<string, list<string>>|null
*/
private array | null $parsedFields = null;
/**
* Register a global callback to resolve the resource ID.
*
* @param Closure(mixed, Request|null): string $callback
*/
public static function resolveIdUsing(Closure $callback): void
{
self::$idResolver = $callback;
}
/**
* Register a global callback to resolve the resource type.
*
* @param Closure(mixed, Request|null): string $callback
*/
public static function resolveTypeUsing(Closure $callback): void
{
self::$typeResolver = $callback;
}
/**
* Reset global resolvers (useful for testing).
*/
public static function resetResolvers(): void
{
self::$idResolver = null;
self::$typeResolver = null;
}
public static function make(mixed ...$data): array | null
{
return app(static::class)->toArray(...$data);
}
public function withRequest(Request | null $request): static
{
$this->request = $request;
$this->parsedFields = null;
return $this;
}
/**
* @param TModel|null $model
*/
public function toArray($model = null): array | null
{
if ($model === null) {
return null;
}
if (! method_exists($this, 'attributes')) {
throw new BadMethodCallException(
static::class.' must implement an attributes() method.',
);
}
$type = $this->resolveType($model);
$attributes = $this->attributes($model);
if ($this->request !== null) {
$attributes = $this->applySparseFieldsets($type, $attributes);
}
return [
'type' => $type,
'id' => $this->resolveId($model),
'attributes' => $attributes,
'relationships' => $this->resolveRelationships($model),
'links' => $this->resolveLinks($model),
'meta' => $this->resolveMeta($model),
];
}
/**
* Define the OpenAPI schema for this resource's attributes.
* Override to provide explicit type definitions for OpenAPI generation.
* When empty, types are inferred from the model's casts and columns.
*
* @return array<string, array<string, mixed>|string>
*/
public function schema(): array
{
return [];
}
/**
* Define the resource relationships.
* Maps relationship name to Resource class.
*
* @return array<string, class-string<resource>>
*/
public function relationships(): array
{
return [];
}
/**
* Define the allowed filters for this resource.
*
* @return array<string, class-string<Filter>|Filter>
*/
public function allowedFilters(): array
{
return [];
}
/**
* Define the allowed sort fields for this resource.
*
* @return list<string>
*/
public function allowedSorts(): array
{
return [];
}
/**
* Define the default sort for this resource.
*/
public function defaultSort(): string | null
{
return null;
}
/**
* Define the allowed includes for this resource.
* Defaults to the keys of relationships() if not overridden.
*
* @return list<string>
*/
public function allowedIncludes(): array
{
return array_keys($this->relationships());
}
/**
* @return class-string<TModel>|string
*/
public function getModel(): string
{
return $this->model;
}
public function resolveType($model = null): string
{
if ($this->type !== '') {
return $this->type;
}
if (self::$typeResolver !== null && $model !== null) {
return (self::$typeResolver)($model, $this->request);
}
if ($this->model !== '') {
return (new $this->model())->getTable();
}
if ($model instanceof Model) {
return $model->getTable();
}
if ($model !== null) {
return Str::snake(class_basename($model), '-');
}
return '';
}
public function resolveId($model): string
{
if (self::$idResolver !== null) {
return (self::$idResolver)($model, $this->request);
}
if ($model instanceof Model) {
return (string) $model->getKey();
}
if (is_object($model) && property_exists($model, 'id')) {
return (string) $model->id;
}
throw new RuntimeException(
sprintf(
'Unable to resolve ID for [%s] in resource [%s]. Define an id property or register a global resolver with Resource::resolveIdUsing().',
get_debug_type($model),
static::class,
),
);
}
/**
* @param mixed $model
*
* @return array<string, string>
*/
private function resolveLinks($model): array
{
$links = [];
if (method_exists($this, 'self')) {
$self = $this->self($model);
if ($self !== null) {
$links['self'] = $self;
}
}
if (method_exists($this, 'links')) {
$links = array_merge($links, $this->links($model));
}
return $links;
}
/**
* @param mixed $model
*
* @return array<string, mixed>
*/
private function resolveMeta($model): array
{
if (method_exists($this, 'meta')) {
return $this->meta($model);
}
return [];
}
/**
* @param array<string, mixed> $attributes
*
* @return array<string, mixed>
*/
private function applySparseFieldsets(string $type, array $attributes): array
{
$parser = new FieldParser();
if ($this->parsedFields === null) {
$this->parsedFields = $parser->parse($this->request);
}
return $parser->filter($attributes, $this->parsedFields[$type] ?? null);
}
/**
* @param mixed $model
*
* @return array<string, array{data: array|null}>
*/
private function resolveRelationships($model): array
{
$resolved = [];
foreach ($this->relationships() as $name => $resourceClass) {
if (! $model instanceof Model || ! $model->relationLoaded($name)) {
continue;
}
$related = $model->getRelation($name);
if ($related === null) {
$resolved[$name] = ['data' => null];
continue;
}
if ($related instanceof \Illuminate\Database\Eloquent\Collection) {
$resource = app($resourceClass)->withRequest($this->request);
$resolved[$name] = [
'data' => $related->map(fn (mixed $item): array => [
'type' => $resource->resolveType($item),
'id' => $resource->resolveId($item),
])->all(),
];
continue;
}
$resource = app($resourceClass)->withRequest($this->request);
$resolved[$name] = [
'data' => [
'type' => $resource->resolveType($related),
'id' => $resource->resolveId($related),
],
];
}
return $resolved;
}
}