Serializer.php 10 KB

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