This repository was archived by the owner on Jan 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathPolymorphicCollection.php
More file actions
125 lines (109 loc) · 2.67 KB
/
PolymorphicCollection.php
File metadata and controls
125 lines (109 loc) · 2.67 KB
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
<?php
/*
* This file is part of JSON-API.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobscure\JsonApi;
class PolymorphicCollection implements ElementInterface
{
/**
* @var array
*/
protected $resources = [];
/**
* Create a new collection instance.
*
* @param mixed $data
* @param \Tobscure\JsonApi\SerializerRegistryInterface $serializers
*/
public function __construct($data, SerializerRegistryInterface $serializers)
{
$this->resources = $this->buildResources($data, $serializers);
}
/**
* Convert an array of raw data to Resource objects.
*
* @param mixed $data
* @param \Tobscure\JsonApi\SerializerRegistryInterface $serializers
* @return \Tobscure\JsonApi\Resource[]
*/
protected function buildResources($data, SerializerRegistryInterface $serializers)
{
$resources = [];
foreach ($data as $resource) {
if (! ($resource instanceof Resource)) {
$resource = new Resource($resource, $serializers->getFromSerializable($resource));
}
$resources[] = $resource;
}
return $resources;
}
/**
* {@inheritdoc}
*/
public function getResources()
{
return $this->resources;
}
/**
* Set the resources array.
*
* @param array $resources
*
* @return void
*/
public function setResources($resources)
{
$this->resources = $resources;
}
/**
* Request a relationship to be included for all resources.
*
* @param string|array $relationships
*
* @return $this
*/
public function with($relationships)
{
foreach ($this->resources as $resource) {
$resource->with($relationships);
}
return $this;
}
/**
* Request a restricted set of fields.
*
* @param array|null $fields
*
* @return $this
*/
public function fields($fields)
{
foreach ($this->resources as $resource) {
$resource->fields($fields);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function toArray()
{
return array_map(function (Resource $resource) {
return $resource->toArray();
}, $this->resources);
}
/**
* {@inheritdoc}
*/
public function toIdentifier()
{
return array_map(function (Resource $resource) {
return $resource->toIdentifier();
}, $this->resources);
}
}