1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Huntie\JsonApi\Serializers; |
4
|
|
|
|
5
|
|
|
use JsonSerializable; |
6
|
|
|
|
7
|
|
|
abstract class JsonApiSerializer implements JsonSerializable |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Meta information to include. |
11
|
|
|
* |
12
|
|
|
* @var \Illuminate\Support\Collection |
13
|
|
|
*/ |
14
|
|
|
protected $meta; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Resource links to include. |
18
|
|
|
* |
19
|
|
|
* @var \Illuminate\Support\Collection |
20
|
|
|
*/ |
21
|
|
|
protected $links; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Create a new JSON API document serializer. |
25
|
|
|
*/ |
26
|
|
|
public function __construct() |
27
|
|
|
{ |
28
|
|
|
$this->meta = collect([]); |
29
|
|
|
$this->links = collect([]); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Return primary data for the JSON API document. |
34
|
|
|
* |
35
|
|
|
* @return array |
36
|
|
|
*/ |
37
|
|
|
abstract protected function getPrimaryData(); |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Add included meta information. |
41
|
|
|
* |
42
|
|
|
* @param string|array $key |
43
|
|
|
* @param string|int|null $value |
44
|
|
|
*/ |
45
|
|
|
public function addMeta($key, $value = null) |
46
|
|
|
{ |
47
|
|
|
$this->meta = $this->meta->merge(is_array($key) ? $key : [$key => $value]); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Add one or more included links. |
52
|
|
|
* |
53
|
|
|
* @param string|array $key |
54
|
|
|
* @param string|int|null $value |
55
|
|
|
*/ |
56
|
|
|
public function addLinks($key, $value = null) |
57
|
|
|
{ |
58
|
|
|
$this->links = $this->links->merge(is_array($key) ? $key : [$key => $value]); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Serialise JSON API document to an array. |
63
|
|
|
* |
64
|
|
|
* @return array |
65
|
|
|
*/ |
66
|
|
|
public function serializeToObject() |
67
|
|
|
{ |
68
|
|
|
return array_filter([ |
69
|
|
|
'data' => $this->getPrimaryData(), |
70
|
|
|
'links' => $this->links->toArray(), |
71
|
|
|
'meta' => $this->meta->toArray(), |
72
|
|
|
'included' => $this->getIncludedData(), |
73
|
|
|
]); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Convert the object into something JSON serializable. |
78
|
|
|
* |
79
|
|
|
* @return array |
80
|
|
|
*/ |
81
|
|
|
public function jsonSerialize() |
82
|
|
|
{ |
83
|
|
|
return $this->serializeToObject(); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Serialise JSON API document to a JSON string. |
88
|
|
|
* |
89
|
|
|
* @return array |
90
|
|
|
*/ |
91
|
|
|
public function serializeToJson() |
92
|
|
|
{ |
93
|
|
|
return json_encode($this->jsonSerialize()); |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
/** |
97
|
|
|
* Return any secondary included resource data. |
98
|
|
|
* |
99
|
|
|
* @return array |
100
|
|
|
*/ |
101
|
|
|
protected function getIncludedData() |
102
|
|
|
{ |
103
|
|
|
return []; |
104
|
|
|
} |
105
|
|
|
} |
106
|
|
|
|