Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

275 lines
9.5KB

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