|
1
|
|
|
<?php namespace Pz\Doctrine\Rest\Fractal; |
|
2
|
|
|
|
|
3
|
|
|
use Pz\Doctrine\Rest\Contracts\RestRequestContract; |
|
4
|
|
|
|
|
5
|
|
|
class JsonApiSerializer extends \League\Fractal\Serializer\JsonApiSerializer |
|
6
|
|
|
{ |
|
7
|
|
|
/** |
|
8
|
|
|
* @var RestRequestContract |
|
9
|
|
|
*/ |
|
10
|
|
|
protected $request; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* JsonApiSerializer constructor. |
|
14
|
|
|
* |
|
15
|
|
|
* @param RestRequestContract $request |
|
16
|
|
|
*/ |
|
17
|
19 |
|
public function __construct(RestRequestContract $request) |
|
18
|
|
|
{ |
|
19
|
19 |
|
parent::__construct($request->getBaseUrl()); |
|
20
|
19 |
|
$this->request = $request; |
|
21
|
19 |
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param string $resourceKey |
|
25
|
|
|
* @param array $data |
|
26
|
|
|
* @param bool $includeAttributes |
|
27
|
|
|
* |
|
28
|
|
|
* @return array |
|
29
|
|
|
*/ |
|
30
|
13 |
|
public function collection($resourceKey, array $data, $includeAttributes = true) |
|
31
|
|
|
{ |
|
32
|
13 |
|
$resources = []; |
|
33
|
|
|
|
|
34
|
13 |
|
foreach ($data as $resource) { |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Add option to override resource key with data. |
|
38
|
|
|
*/ |
|
39
|
13 |
|
if (is_array($resource) && array_key_exists('_resource_key', $resource)) { |
|
40
|
|
|
$resourceKey = $resource['_resource_key']; |
|
41
|
|
|
unset($resource['_resource_key']); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
13 |
|
$resources[] = $this->item($resourceKey, $resource, $includeAttributes)['data']; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
13 |
|
return ['data' => $resources]; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @param string $resourceKey |
|
52
|
|
|
* @param array $data |
|
53
|
|
|
* @param bool $includeAttributes |
|
54
|
|
|
* |
|
55
|
|
|
* @return array |
|
56
|
|
|
*/ |
|
57
|
19 |
|
public function item($resourceKey, array $data, $includeAttributes = true) |
|
58
|
|
|
{ |
|
59
|
19 |
|
$item = parent::item($resourceKey, $data); |
|
60
|
19 |
|
if (!$includeAttributes) { |
|
61
|
4 |
|
unset($item['data']['attributes']); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
19 |
|
return $item; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|