This repository has been archived by the owner on Apr 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
AbstractEloquentResource.php
382 lines (323 loc) · 11 KB
/
AbstractEloquentResource.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
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
<?php
namespace Czim\JsonApi\Support\Resource;
use Czim\JsonApi\Contracts\Repositories\ResourceRepositoryInterface;
use Czim\JsonApi\Contracts\Resource\EloquentResourceInterface;
use Czim\JsonApi\Contracts\Support\Type\TypeMakerInterface;
use Czim\JsonApi\Exceptions\InvalidIncludeException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Str;
use RuntimeException;
use UnexpectedValueException;
abstract class AbstractEloquentResource extends AbstractJsonApiResource implements EloquentResourceInterface
{
/**
* @var Model
*/
protected $model;
/**
* Optional mapping for includes to Eloquent relation methods.
*
* For instance:
*
* 'your-include' => 'includeMethod'
*
* Would make 'your-include' refer to model->includeMethod() to access the relation.
*
* @var string[] associative, keyed by include key
*/
protected $includeRelations = [];
/**
* Sets the model instance to use.
*
* This should be done before calling any other method, unless
* a model is guaranteed to be set using the constructor.
*
* @param Model $model
* @return $this
*/
public function setModel(Model $model): EloquentResourceInterface
{
$this->model = $model;
return $this;
}
public function getModel(): ?Model
{
return $this->model;
}
/**
* Returns the JSON-API type.
*
* @return string
*/
public function type(): string
{
return $this->getTypeMaker()->makeForModelClass($this->getModelClass());
}
/**
* Returns the JSON-API ID.
*
* @return string
*/
public function id(): string
{
return (string) $this->model->getKey();
}
/**
* Returns an attribute value, directly from the model, or decorated for the resource.
*
* @param string $name attribute name or key
* @param mixed $default
* @return mixed
*/
public function attributeValue(string $name, $default = null)
{
$accessorMethod = 'get' . Str::studly(str_replace('-', ' ', $name)) . 'Attribute';
if (method_exists($this, $accessorMethod)) {
$value = call_user_func([ $this, $accessorMethod ]);
} else {
$value = $this->model->{$this->getModelAttributeForApiAttribute($name)};
}
if ($this->isAttributeDate($name, $value)) {
$value = $this->formatDate($value, $this->getConfiguredFormatForAttribute($name));
}
return null !== $value ? $value : $default;
}
/**
* Returns the model attribute for a given JSON-API attribute, if available.
*
* @param string $name
* @return string|null
*/
public function getModelAttributeForApiAttribute(string $name): ?string
{
return Str::snake($name);
}
/**
* Returns reference-only data for relationship include.
*
* @todo deal with variable relation content (variable keys, & json-api types)
*
* @param string $include
* @return array|array[]|null
*/
public function relationshipReferences(string $include): ?array
{
$method = $this->getRelationMethodForInclude($include);
$relation = $this->getModelRelation($method);
$singular = $this->isSingularRelation($relation);
$variable = $this->isVariableModelRelation($relation);
$relatedModel = $this->getRelatedModelForRelation($relation);
// Safeguard: if we cannot determine the model, there may be an issue,
// or it may simply be an unset morphTo relation.
if ( ! $relatedModel) {
if ($variable) {
return $singular ? null : [];
}
// @codeCoverageIgnoreStart
throw new UnexpectedValueException("Could not determine related model for related reference data lookup");
// @codeCoverageIgnoreEnd
}
$relatedResource = $this->getResourceRepository()->getByModel($relatedModel);
if ( ! $relatedResource) {
throw new RuntimeException("Could not determine resource for model '" . get_class($relatedModel) . "'");
}
if ($this->model->relationLoaded($method)) {
if ($singular) {
if ($this->model->{$method}) {
$ids = [ $this->model->{$method}->{$relatedModel->getKeyName()} ];
} else {
$ids = [];
}
} else {
$ids = $this->model->{$method}->pluck($relatedModel->getKeyName())->toArray();
}
} else {
// If the relation is singular, we just need the id so no need to query
// the entire model.
if ($relation instanceof Relations\BelongsTo) {
$foreignKeyName = $relation->getForeignKeyName();
$id = $this->model->getAttribute($foreignKeyName);
if ($id !== null) {
$ids[] = $id;
} else {
$ids = [];
}
} else {
$ids = $relation->pluck($relatedModel->getQualifiedKeyName())->toArray();
}
}
if ($singular) {
if ( ! count($ids)) {
return null;
}
return [ 'type' => $relatedResource->type(), 'id' => (string) head($ids) ];
}
return array_map(
function ($id) use ($relatedResource) {
return [ 'type' => $relatedResource->type(), 'id' => (string) $id ];
},
$ids
);
}
/**
* Returns full data for relationship include.
*
* @param string $include
* @return Model|\Illuminate\Support\Collection|null
*/
public function relationshipData(string $include)
{
$includeKey = $include;
$method = $this->getRelationMethodForInclude($includeKey);
return $this->getModel()->{$method};
}
/**
* Returns the JSON-API type for a given include.
*
* @param string $include
* @return null|string
*/
public function relationshipType(string $include): ?string
{
// If the relationship is variable, we can only give a type if it is both singular and filled
$relation = $this->includeRelation($include);
if ($this->isVariableModelRelation($relation)) {
// @codeCoverageIgnoreStart
if ( ! $this->isSingularRelation($relation)) {
return null;
}
// Get the type for the actually related item
/** @var Relations\MorphTo $relation */
$modelClass = $this->model->{$relation->getMorphType()};
if ( ! $modelClass || ! is_a($modelClass, Model::class, true)) {
return null;
}
return $this->getTypeMaker()->makeFor(new $modelClass);
// @codeCoverageIgnoreEnd
}
return $this->getTypeMaker()->makeFor(
$this->getRelatedModelForRelation(
$this->includeRelation($include)
)
);
}
/**
* Returns whether a given include belongs to a singular relationship.
*
* @param string $include
* @return bool
*/
public function isRelationshipSingular(string $include): bool
{
return $this->isSingularRelation(
$this->includeRelation($include)
);
}
/**
* Returns whether a given include belongs to a relationship with variable content.
*
* @param string $include
* @return bool
*/
public function isRelationshipVariable(string $include): bool
{
return $this->isVariableModelRelation(
$this->includeRelation($include)
);
}
/**
* Returns the Eloquent relation method for an include key/name, if possible.
*
* @param string $name
* @return Relation|null
* @throws InvalidIncludeException
*/
public function includeRelation(string $name): ?Relation
{
$method = $this->getRelationMethodForInclude($name);
return $this->getModelRelation($method);
}
/**
* Returns the Eloquent relation method for a given include name.
*
* @param string $name
* @return string
* @throws InvalidIncludeException
*/
public function getRelationMethodForInclude(string $name): string
{
if ( ! in_array($name, $this->availableIncludes())) {
throw new InvalidIncludeException("'{$name}' is not a valid include for '" . get_class($this) . "'");
}
if (empty($this->includeRelations) || ! array_key_exists($name, $this->includeRelations)) {
return $name;
}
return $this->includeRelations[ $name ];
}
/**
* Returns relation type string for include method name from Eloquent model.
*
* @param string $method
* @return Relation|Builder
*/
protected function getModelRelation(string $method)
{
$model = $this->getModel();
$relationMethod = Str::camel($method);
if ( ! method_exists($model, $relationMethod)) {
throw new RuntimeException(
"No method '{$relationMethod}' exists on model " . get_class($model) . " for relation '{$method}"
);
}
$relation = $model->{$relationMethod}();
if ( ! ($relation instanceof Relations\Relation)) {
throw new RuntimeException(
"Method '{$relationMethod}' on model " . get_class($model) . " is not a relation method"
);
}
return $relation;
}
/**
* Returns the model instance for a relation.
*
* @param Relation $relation
* @return Model|null
*/
protected function getRelatedModelForRelation(Relation $relation): ?Model
{
if ($relation instanceof Relations\MorphTo) {
$modelClass = $this->model->{$relation->getMorphType()};
if ($modelClass && is_a($modelClass, Model::class, true)) {
return new $modelClass;
}
return null;
}
return $relation->getRelated();
}
protected function isSingularRelation(Relation $relation): bool
{
return $relation instanceof Relations\BelongsTo
|| $relation instanceof Relations\HasOne
|| $relation instanceof Relations\MorphOne
|| $relation instanceof Relations\MorphTo;
}
protected function isVariableModelRelation(Relation $relation): bool
{
return $relation instanceof Relations\MorphTo;
}
protected function getModelClass(): string
{
return get_class($this->model);
}
protected function getTypeMaker(): TypeMakerInterface
{
return app(TypeMakerInterface::class);
}
protected function getResourceRepository(): ResourceRepositoryInterface
{
return app(ResourceRepositoryInterface::class);
}
}