Completed
Pull Request — 2.1 (#12704)
by Robert
08:59
created

Serializer   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 254
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 79.01%

Importance

Changes 0
Metric Value
wmc 27
lcom 1
cbo 11
dl 0
loc 254
ccs 64
cts 81
cp 0.7901
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 9 3
A serializePagination() 0 12 1
A serializeModel() 0 9 2
A getRequestedFields() 0 10 3
B serialize() 0 12 5
B serializeDataProvider() 0 23 5
A addPaginationHeaders() 0 14 2
A serializeModelErrors() 0 13 2
A serializeModels() 0 13 4
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
114
    /**
115
     * @inheritdoc
116
     */
117 30
    public function init()
118
    {
119 30
        if ($this->request === null) {
120 30
            $this->request = Yii::$app->getRequest();
121 30
        }
122 30
        if ($this->response === null) {
123 30
            $this->response = Yii::$app->getResponse();
124 30
        }
125 30
    }
126
127
    /**
128
     * Serializes the given data into a format that can be easily turned into other formats.
129
     * This method mainly converts the objects of recognized types into array representation.
130
     * It will not do conversion for unknown object types or non-object data.
131
     * The default implementation will handle [[Model]] and [[DataProviderInterface]].
132
     * You may override this method to support more object types.
133
     * @param mixed $data the data to be serialized.
134
     * @return mixed the converted data.
135
     */
136 30
    public function serialize($data)
137
    {
138 30
        if ($data instanceof Model && $data->hasErrors()) {
139 1
            return $this->serializeModelErrors($data);
140 29
        } elseif ($data instanceof Arrayable) {
141 3
            return $this->serializeModel($data);
142 26
        } elseif ($data instanceof DataProviderInterface) {
143 3
            return $this->serializeDataProvider($data);
144
        } else {
145 23
            return $data;
146
        }
147
    }
148
149
    /**
150
     * @return array the names of the requested fields. The first element is an array
151
     * representing the list of default fields requested, while the second element is
152
     * an array of the extra fields requested in addition to the default fields.
153
     * @see Model::fields()
154
     * @see Model::extraFields()
155
     */
156 6
    protected function getRequestedFields()
157
    {
158 6
        $fields = $this->request->get($this->fieldsParam);
159 6
        $expand = $this->request->get($this->expandParam);
160
161
        return [
162 6
            is_string($fields) ? preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY) : [],
163 6
            is_string($expand) ? preg_split('/\s*,\s*/', $expand, -1, PREG_SPLIT_NO_EMPTY) : [],
164 6
        ];
165
    }
166
167
    /**
168
     * Serializes a data provider.
169
     * @param DataProviderInterface $dataProvider
170
     * @return array the array representation of the data provider.
171
     */
172 3
    protected function serializeDataProvider($dataProvider)
173
    {
174 3
        $models = $this->serializeModels(array_values($dataProvider->getModels()));
175
176 3
        if (($pagination = $dataProvider->getPagination()) !== false) {
177 3
            $this->addPaginationHeaders($pagination);
178 3
        }
179
180 3
        if ($this->request->getIsHead()) {
181
            return null;
182 3
        } elseif ($this->collectionEnvelope === null) {
183 3
            return $models;
184
        } else {
185
            $result = [
186
                $this->collectionEnvelope => $models,
187
            ];
188
            if ($pagination !== false) {
189
                return array_merge($result, $this->serializePagination($pagination));
190
            } else {
191
                return $result;
192
            }
193
        }
194
    }
195
196
    /**
197
     * Serializes a pagination into an array.
198
     * @param Pagination $pagination
199
     * @return array the array representation of the pagination
200
     * @see addPaginationHeaders()
201
     */
202
    protected function serializePagination($pagination)
203
    {
204
        return [
205
            $this->linksEnvelope => Link::serialize($pagination->getLinks(true)),
206
            $this->metaEnvelope => [
207
                'totalCount' => $pagination->totalCount,
208
                'pageCount' => $pagination->getPageCount(),
209
                'currentPage' => $pagination->getPage() + 1,
210
                'perPage' => $pagination->getPageSize(),
211
            ],
212
        ];
213
    }
214
215
    /**
216
     * Adds HTTP headers about the pagination to the response.
217
     * @param Pagination $pagination
218
     */
219 3
    protected function addPaginationHeaders($pagination)
220
    {
221 3
        $links = [];
222 3
        foreach ($pagination->getLinks(true) as $rel => $url) {
223 3
            $links[] = "<$url>; rel=$rel";
224 3
        }
225
226 3
        $this->response->getHeaders()
227 3
            ->set($this->totalCountHeader, $pagination->totalCount)
228 3
            ->set($this->pageCountHeader, $pagination->getPageCount())
229 3
            ->set($this->currentPageHeader, $pagination->getPage() + 1)
230 3
            ->set($this->perPageHeader, $pagination->pageSize)
231 3
            ->set('Link', implode(', ', $links));
232 3
    }
233
234
    /**
235
     * Serializes a model object.
236
     * @param Arrayable $model
237
     * @return array the array representation of the model
238
     */
239 3
    protected function serializeModel($model)
240
    {
241 3
        if ($this->request->getIsHead()) {
242
            return null;
243
        } else {
244 3
            list ($fields, $expand) = $this->getRequestedFields();
245 3
            return $model->toArray($fields, $expand);
246
        }
247
    }
248
249
    /**
250
     * Serializes the validation errors in a model.
251
     * @param Model $model
252
     * @return array the array representation of the errors
253
     */
254 1
    protected function serializeModelErrors($model)
255
    {
256 1
        $this->response->setStatusCode(422, 'Data Validation Failed.');
257 1
        $result = [];
258 1
        foreach ($model->getFirstErrors() as $name => $message) {
259 1
            $result[] = [
260 1
                'field' => $name,
261 1
                'message' => $message,
262
            ];
263 1
        }
264
265 1
        return $result;
266
    }
267
268
    /**
269
     * Serializes a set of models.
270
     * @param array $models
271
     * @return array the array representation of the models
272
     */
273 3
    protected function serializeModels(array $models)
274
    {
275 3
        list ($fields, $expand) = $this->getRequestedFields();
276 3
        foreach ($models as $i => $model) {
277 3
            if ($model instanceof Arrayable) {
278
                $models[$i] = $model->toArray($fields, $expand);
279 3
            } elseif (is_array($model)) {
280 3
                $models[$i] = ArrayHelper::toArray($model);
281 3
            }
282 3
        }
283
284 3
        return $models;
285
    }
286
}
287