Serializer.php 9.9KB

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