|
6 | 6 | use Swis\JsonApi\Client\Interfaces\DataInterface; |
7 | 7 | use Swis\JsonApi\Client\Interfaces\DocumentInterface; |
8 | 8 |
|
9 | | -class Document implements DocumentInterface |
| 9 | +class Document implements DocumentInterface, \JsonSerializable |
10 | 10 | { |
11 | 11 | /** |
12 | 12 | * @var \Swis\JsonApi\Client\Interfaces\DataInterface |
@@ -155,4 +155,53 @@ public function setData(DataInterface $data) |
155 | 155 |
|
156 | 156 | return $this; |
157 | 157 | } |
| 158 | + |
| 159 | + /** |
| 160 | + * Specify data which should be serialized to JSON. |
| 161 | + * |
| 162 | + * @see http://php.net/manual/en/jsonserializable.jsonserialize.php |
| 163 | + * |
| 164 | + * @return mixed data which can be serialized by <b>json_encode</b>, |
| 165 | + * which is a value of any type other than a resource |
| 166 | + * |
| 167 | + * @since 5.4.0 |
| 168 | + */ |
| 169 | + public function jsonSerialize() |
| 170 | + { |
| 171 | + return $this->toArray(); |
| 172 | + } |
| 173 | + |
| 174 | + /** |
| 175 | + * @return array |
| 176 | + */ |
| 177 | + public function toArray(): array |
| 178 | + { |
| 179 | + $document = []; |
| 180 | + |
| 181 | + if (!empty($this->getLinks())) { |
| 182 | + $document['links'] = $this->links; |
| 183 | + } |
| 184 | + |
| 185 | + if (!empty($this->getData())) { |
| 186 | + $document['data'] = $this->data->toJsonApiArray(); |
| 187 | + } |
| 188 | + |
| 189 | + if ($this->getIncluded()->isNotEmpty()) { |
| 190 | + $document['included'] = $this->getIncluded()->toJsonApiArray(); |
| 191 | + } |
| 192 | + |
| 193 | + if (!empty($this->getMeta())) { |
| 194 | + $document['meta'] = $this->meta; |
| 195 | + } |
| 196 | + |
| 197 | + if ($this->hasErrors()) { |
| 198 | + $document['errors'] = $this->errors->toArray(); |
| 199 | + } |
| 200 | + |
| 201 | + if (!empty($this->getJsonapi())) { |
| 202 | + $document['jsonapi'] = $this->jsonapi; |
| 203 | + } |
| 204 | + |
| 205 | + return $document; |
| 206 | + } |
158 | 207 | } |
0 commit comments