1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link http://www.yiiframework.com/ |
4
|
|
|
* @copyright Copyright (c) 2008 Yii Software LLC |
5
|
|
|
* @license http://www.yiiframework.com/license/ |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yii\rest; |
9
|
|
|
|
10
|
|
|
use Yii; |
11
|
|
|
use yii\base\Arrayable; |
12
|
|
|
use yii\base\Component; |
13
|
|
|
use yii\base\Model; |
14
|
|
|
use yii\data\DataProviderInterface; |
15
|
|
|
use yii\data\Pagination; |
16
|
|
|
use yii\helpers\ArrayHelper; |
17
|
|
|
use yii\web\Link; |
18
|
|
|
use yii\web\Request; |
19
|
|
|
use yii\web\Response; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Serializer converts resource objects and collections into array representation. |
23
|
|
|
* |
24
|
|
|
* Serializer is mainly used by REST controllers to convert different objects into array representation |
25
|
|
|
* so that they can be further turned into different formats, such as JSON, XML, by response formatters. |
26
|
|
|
* |
27
|
|
|
* The default implementation handles resources as [[Model]] objects and collections as objects |
28
|
|
|
* implementing [[DataProviderInterface]]. You may override [[serialize()]] to handle more types. |
29
|
|
|
* |
30
|
|
|
* @author Qiang Xue <[email protected]> |
31
|
|
|
* @since 2.0 |
32
|
|
|
*/ |
33
|
|
|
class Serializer extends Component |
34
|
|
|
{ |
35
|
|
|
/** |
36
|
|
|
* @var string the name of the query parameter containing the information about which fields should be returned |
37
|
|
|
* for a [[Model]] object. If the parameter is not provided or empty, the default set of fields as defined |
38
|
|
|
* by [[Model::fields()]] will be returned. |
39
|
|
|
*/ |
40
|
|
|
public $fieldsParam = 'fields'; |
41
|
|
|
/** |
42
|
|
|
* @var string the name of the query parameter containing the information about which fields should be returned |
43
|
|
|
* in addition to those listed in [[fieldsParam]] for a resource object. |
44
|
|
|
*/ |
45
|
|
|
public $expandParam = 'expand'; |
46
|
|
|
/** |
47
|
|
|
* @var string the name of the HTTP header containing the information about total number of data items. |
48
|
|
|
* This is used when serving a resource collection with pagination. |
49
|
|
|
*/ |
50
|
|
|
public $totalCountHeader = 'X-Pagination-Total-Count'; |
51
|
|
|
/** |
52
|
|
|
* @var string the name of the HTTP header containing the information about total number of pages of data. |
53
|
|
|
* This is used when serving a resource collection with pagination. |
54
|
|
|
*/ |
55
|
|
|
public $pageCountHeader = 'X-Pagination-Page-Count'; |
56
|
|
|
/** |
57
|
|
|
* @var string the name of the HTTP header containing the information about the current page number (1-based). |
58
|
|
|
* This is used when serving a resource collection with pagination. |
59
|
|
|
*/ |
60
|
|
|
public $currentPageHeader = 'X-Pagination-Current-Page'; |
61
|
|
|
/** |
62
|
|
|
* @var string the name of the HTTP header containing the information about the number of data items in each page. |
63
|
|
|
* This is used when serving a resource collection with pagination. |
64
|
|
|
*/ |
65
|
|
|
public $perPageHeader = 'X-Pagination-Per-Page'; |
66
|
|
|
/** |
67
|
|
|
* @var string the name of the envelope (e.g. `items`) for returning the resource objects in a collection. |
68
|
|
|
* This is used when serving a resource collection. When this is set and pagination is enabled, the serializer |
69
|
|
|
* will return a collection in the following format: |
70
|
|
|
* |
71
|
|
|
* ```php |
72
|
|
|
* [ |
73
|
|
|
* 'items' => [...], // assuming collectionEnvelope is "items" |
74
|
|
|
* '_links' => { // pagination links as returned by Pagination::getLinks() |
75
|
|
|
* 'self' => '...', |
76
|
|
|
* 'next' => '...', |
77
|
|
|
* 'last' => '...', |
78
|
|
|
* }, |
79
|
|
|
* '_meta' => { // meta information as returned by Pagination::toArray() |
80
|
|
|
* 'totalCount' => 100, |
81
|
|
|
* 'pageCount' => 5, |
82
|
|
|
* 'currentPage' => 1, |
83
|
|
|
* 'perPage' => 20, |
84
|
|
|
* }, |
85
|
|
|
* ] |
86
|
|
|
* ``` |
87
|
|
|
* |
88
|
|
|
* If this property is not set, the resource arrays will be directly returned without using envelope. |
89
|
|
|
* The pagination information as shown in `_links` and `_meta` can be accessed from the response HTTP headers. |
90
|
|
|
*/ |
91
|
|
|
public $collectionEnvelope; |
92
|
|
|
/** |
93
|
|
|
* @var string the name of the envelope (e.g. `_links`) for returning the links objects. |
94
|
|
|
* It takes effect only, if `collectionEnvelope` is set. |
95
|
|
|
* @since 2.0.4 |
96
|
|
|
*/ |
97
|
|
|
public $linksEnvelope = '_links'; |
98
|
|
|
/** |
99
|
|
|
* @var string the name of the envelope (e.g. `_meta`) for returning the pagination object. |
100
|
|
|
* It takes effect only, if `collectionEnvelope` is set. |
101
|
|
|
* @since 2.0.4 |
102
|
|
|
*/ |
103
|
|
|
public $metaEnvelope = '_meta'; |
104
|
|
|
/** |
105
|
|
|
* @var Request the current request. If not set, the `request` application component will be used. |
106
|
|
|
*/ |
107
|
|
|
public $request; |
108
|
|
|
/** |
109
|
|
|
* @var Response the response to be sent. If not set, the `response` application component will be used. |
110
|
|
|
*/ |
111
|
|
|
public $response; |
112
|
|
|
/** |
113
|
|
|
* @var bool whether to preserve array keys when serializing collection data. |
114
|
|
|
* Set this to `true` to allow serialization of a collection as a JSON object where array keys are |
115
|
|
|
* used to index the model objects. The default is to serialize all collections as array, regardless |
116
|
|
|
* of how the array is indexed. |
117
|
|
|
* @see serializeDataProvider() |
118
|
|
|
* @since 2.0.10 |
119
|
|
|
*/ |
120
|
|
|
public $preserveKeys = false; |
121
|
|
|
|
122
|
|
|
|
123
|
|
|
/** |
124
|
|
|
* {@inheritdoc} |
125
|
|
|
*/ |
126
|
65 |
|
public function init() |
127
|
|
|
{ |
128
|
65 |
|
if ($this->request === null) { |
129
|
65 |
|
$this->request = Yii::$app->getRequest(); |
130
|
|
|
} |
131
|
65 |
|
if ($this->response === null) { |
132
|
65 |
|
$this->response = Yii::$app->getResponse(); |
133
|
|
|
} |
134
|
65 |
|
} |
135
|
|
|
|
136
|
|
|
/** |
137
|
|
|
* Serializes the given data into a format that can be easily turned into other formats. |
138
|
|
|
* This method mainly converts the objects of recognized types into array representation. |
139
|
|
|
* It will not do conversion for unknown object types or non-object data. |
140
|
|
|
* The default implementation will handle [[Model]] and [[DataProviderInterface]]. |
141
|
|
|
* You may override this method to support more object types. |
142
|
|
|
* @param mixed $data the data to be serialized. |
143
|
|
|
* @return mixed the converted data. |
144
|
|
|
*/ |
145
|
65 |
|
public function serialize($data) |
146
|
|
|
{ |
147
|
65 |
|
if ($data instanceof Model && $data->hasErrors()) { |
148
|
1 |
|
return $this->serializeModelErrors($data); |
149
|
64 |
|
} elseif ($data instanceof Arrayable) { |
150
|
5 |
|
return $this->serializeModel($data); |
151
|
59 |
|
} elseif ($data instanceof DataProviderInterface) { |
152
|
|
|
return $this->serializeDataProvider($data); |
153
|
|
|
} |
154
|
|
|
|
155
|
59 |
|
return $data; |
156
|
|
|
} |
157
|
|
|
|
158
|
|
|
/** |
159
|
|
|
* @return array the names of the requested fields. The first element is an array |
160
|
|
|
* representing the list of default fields requested, while the second element is |
161
|
|
|
* an array of the extra fields requested in addition to the default fields. |
162
|
|
|
* @see Model::fields() |
163
|
|
|
* @see Model::extraFields() |
164
|
|
|
*/ |
165
|
5 |
|
protected function getRequestedFields() |
166
|
|
|
{ |
167
|
5 |
|
$fields = $this->request->get($this->fieldsParam); |
168
|
5 |
|
$expand = $this->request->get($this->expandParam); |
169
|
|
|
|
170
|
|
|
return [ |
171
|
5 |
|
is_string($fields) ? preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY) : [], |
172
|
5 |
|
is_string($expand) ? preg_split('/\s*,\s*/', $expand, -1, PREG_SPLIT_NO_EMPTY) : [], |
173
|
|
|
]; |
174
|
|
|
} |
175
|
|
|
|
176
|
|
|
/** |
177
|
|
|
* Serializes a data provider. |
178
|
|
|
* @param DataProviderInterface $dataProvider |
179
|
|
|
* @return array the array representation of the data provider. |
180
|
|
|
*/ |
181
|
|
|
protected function serializeDataProvider($dataProvider) |
182
|
|
|
{ |
183
|
|
|
if ($this->preserveKeys) { |
184
|
|
|
$models = $dataProvider->getModels(); |
185
|
|
|
} else { |
186
|
|
|
$models = array_values($dataProvider->getModels()); |
187
|
|
|
} |
188
|
|
|
$models = $this->serializeModels($models); |
189
|
|
|
|
190
|
|
|
if (($pagination = $dataProvider->getPagination()) !== false) { |
191
|
|
|
$this->addPaginationHeaders($pagination); |
192
|
|
|
} |
193
|
|
|
|
194
|
|
|
if ($this->request->getIsHead()) { |
195
|
|
|
return null; |
196
|
|
|
} elseif ($this->collectionEnvelope === null) { |
197
|
|
|
return $models; |
198
|
|
|
} |
199
|
|
|
|
200
|
|
|
$result = [ |
201
|
|
|
$this->collectionEnvelope => $models, |
202
|
|
|
]; |
203
|
|
|
if ($pagination !== false) { |
204
|
|
|
return array_merge($result, $this->serializePagination($pagination)); |
205
|
|
|
} |
206
|
|
|
|
207
|
|
|
return $result; |
208
|
|
|
} |
209
|
|
|
|
210
|
|
|
/** |
211
|
|
|
* Serializes a pagination into an array. |
212
|
|
|
* @param Pagination $pagination |
213
|
|
|
* @return array the array representation of the pagination |
214
|
|
|
* @see addPaginationHeaders() |
215
|
|
|
*/ |
216
|
|
|
protected function serializePagination($pagination) |
217
|
|
|
{ |
218
|
|
|
return [ |
219
|
|
|
$this->linksEnvelope => Link::serialize($pagination->getLinks(true)), |
220
|
|
|
$this->metaEnvelope => [ |
221
|
|
|
'totalCount' => $pagination->totalCount, |
222
|
|
|
'pageCount' => $pagination->getPageCount(), |
223
|
|
|
'currentPage' => $pagination->getPage() + 1, |
224
|
|
|
'perPage' => $pagination->getPageSize(), |
225
|
|
|
], |
226
|
|
|
]; |
227
|
|
|
} |
228
|
|
|
|
229
|
|
|
/** |
230
|
|
|
* Adds HTTP headers about the pagination to the response. |
231
|
|
|
* @param Pagination $pagination |
232
|
|
|
*/ |
233
|
|
|
protected function addPaginationHeaders($pagination) |
234
|
|
|
{ |
235
|
|
|
$links = []; |
236
|
|
|
foreach ($pagination->getLinks(true) as $rel => $url) { |
237
|
|
|
$links[] = "<$url>; rel=$rel"; |
238
|
|
|
} |
239
|
|
|
|
240
|
|
|
$this->response->getHeaders() |
241
|
|
|
->set($this->totalCountHeader, $pagination->totalCount) |
242
|
|
|
->set($this->pageCountHeader, $pagination->getPageCount()) |
243
|
|
|
->set($this->currentPageHeader, $pagination->getPage() + 1) |
244
|
|
|
->set($this->perPageHeader, $pagination->pageSize) |
245
|
|
|
->set('Link', implode(', ', $links)); |
246
|
|
|
} |
247
|
|
|
|
248
|
|
|
/** |
249
|
|
|
* Serializes a model object. |
250
|
|
|
* @param Arrayable $model |
251
|
|
|
* @return array the array representation of the model |
252
|
|
|
*/ |
253
|
5 |
|
protected function serializeModel($model) |
254
|
|
|
{ |
255
|
5 |
|
if ($this->request->getIsHead()) { |
256
|
|
|
return null; |
257
|
|
|
} |
258
|
|
|
|
259
|
5 |
|
list($fields, $expand) = $this->getRequestedFields(); |
260
|
5 |
|
return $model->toArray($fields, $expand); |
261
|
|
|
} |
262
|
|
|
|
263
|
|
|
/** |
264
|
|
|
* Serializes the validation errors in a model. |
265
|
|
|
* @param Model $model |
266
|
|
|
* @return array the array representation of the errors |
267
|
|
|
*/ |
268
|
1 |
|
protected function serializeModelErrors($model) |
269
|
|
|
{ |
270
|
1 |
|
$this->response->setStatusCode(422, 'Data Validation Failed.'); |
271
|
1 |
|
$result = []; |
272
|
1 |
|
foreach ($model->getFirstErrors() as $name => $message) { |
273
|
1 |
|
$result[] = [ |
274
|
1 |
|
'field' => $name, |
275
|
1 |
|
'message' => $message, |
276
|
|
|
]; |
277
|
|
|
} |
278
|
|
|
|
279
|
1 |
|
return $result; |
280
|
|
|
} |
281
|
|
|
|
282
|
|
|
/** |
283
|
|
|
* Serializes a set of models. |
284
|
|
|
* @param array $models |
285
|
|
|
* @return array the array representation of the models |
286
|
|
|
*/ |
287
|
|
|
protected function serializeModels(array $models) |
288
|
|
|
{ |
289
|
|
|
list($fields, $expand) = $this->getRequestedFields(); |
290
|
|
|
foreach ($models as $i => $model) { |
291
|
|
|
if ($model instanceof Arrayable) { |
292
|
|
|
$models[$i] = $model->toArray($fields, $expand); |
293
|
|
|
} elseif (is_array($model)) { |
294
|
|
|
$models[$i] = ArrayHelper::toArray($model); |
295
|
|
|
} |
296
|
|
|
} |
297
|
|
|
|
298
|
|
|
return $models; |
299
|
|
|
} |
300
|
|
|
} |
301
|
|
|
|