1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Flugg\Responder\Resources; |
4
|
|
|
|
5
|
|
|
use Flugg\Responder\Pagination\CursorPaginator; |
6
|
|
|
use Illuminate\Contracts\Pagination\Paginator; |
7
|
|
|
use Illuminate\Database\Eloquent\Builder as EloquentBuilder; |
8
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo; |
9
|
|
|
use Illuminate\Database\Eloquent\Relations\HasOne; |
10
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphOne; |
11
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphTo; |
12
|
|
|
use Illuminate\Database\Eloquent\Relations\Relation; |
13
|
|
|
use Illuminate\Database\Query\Builder; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* This class is responsible for normalizing resource data. |
17
|
|
|
* |
18
|
|
|
* @package flugger/laravel-responder |
19
|
|
|
* @author Alexander Tømmerås <[email protected]> |
20
|
|
|
* @license The MIT License |
21
|
|
|
*/ |
22
|
|
|
class DataNormalizer |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* Normalize the data for a resource. |
26
|
|
|
* |
27
|
|
|
* @param mixed $data |
28
|
|
|
* @return mixed |
29
|
|
|
*/ |
30
|
63 |
|
public function normalize($data = null) |
31
|
|
|
{ |
32
|
63 |
|
if ($this->isInstanceOf($data, [Builder::class, EloquentBuilder::class, CursorPaginator::class])) { |
33
|
3 |
|
return $data->get(); |
34
|
60 |
|
} elseif ($data instanceof Paginator) { |
35
|
2 |
|
return $data->getCollection(); |
36
|
58 |
|
} elseif ($data instanceof Relation) { |
37
|
4 |
|
return $this->normalizeRelation($data); |
38
|
|
|
} |
39
|
|
|
|
40
|
54 |
|
return $data; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Normalize a relationship. |
45
|
|
|
* |
46
|
|
|
* @param \Illuminate\Database\Eloquent\Relations\Relation $relation |
47
|
|
|
* @return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|null |
48
|
|
|
*/ |
49
|
4 |
|
protected function normalizeRelation(Relation $relation) |
50
|
|
|
{ |
51
|
4 |
|
if ($this->isInstanceOf($relation, [BelongsTo::class, HasOne::class, MorphOne::class, MorphTo::class])) { |
52
|
2 |
|
return $relation->first(); |
53
|
|
|
} |
54
|
|
|
|
55
|
2 |
|
return $relation->get(); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Indicates if the given data is an instance of any of the given class names. |
60
|
|
|
* |
61
|
|
|
* @param mixed $data |
62
|
|
|
* @param array $classes |
63
|
|
|
* @return bool |
64
|
|
|
*/ |
65
|
63 |
|
protected function isInstanceOf($data, array $classes): bool |
66
|
|
|
{ |
67
|
63 |
|
foreach ($classes as $class) { |
68
|
63 |
|
if ($data instanceof $class) { |
69
|
63 |
|
return true; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
60 |
|
return false; |
74
|
|
|
} |
75
|
|
|
} |