You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 8 година
пре 8 година
пре 8 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. } else {
  148. return $data;
  149. }
  150. }
  151. /**
  152. * @return array the names of the requested fields. The first element is an array
  153. * representing the list of default fields requested, while the second element is
  154. * an array of the extra fields requested in addition to the default fields.
  155. * @see Model::fields()
  156. * @see Model::extraFields()
  157. */
  158. protected function getRequestedFields()
  159. {
  160. $fields = $this->request->get($this->fieldsParam);
  161. $expand = $this->request->get($this->expandParam);
  162. return [
  163. is_string($fields) ? preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY) : [],
  164. is_string($expand) ? preg_split('/\s*,\s*/', $expand, -1, PREG_SPLIT_NO_EMPTY) : [],
  165. ];
  166. }
  167. /**
  168. * Serializes a data provider.
  169. * @param DataProviderInterface $dataProvider
  170. * @return array the array representation of the data provider.
  171. */
  172. protected function serializeDataProvider($dataProvider)
  173. {
  174. if ($this->preserveKeys) {
  175. $models = $dataProvider->getModels();
  176. } else {
  177. $models = array_values($dataProvider->getModels());
  178. }
  179. $models = $this->serializeModels($models);
  180. if (($pagination = $dataProvider->getPagination()) !== false) {
  181. $this->addPaginationHeaders($pagination);
  182. }
  183. if ($this->request->getIsHead()) {
  184. return null;
  185. } elseif ($this->collectionEnvelope === null) {
  186. return $models;
  187. } else {
  188. $result = [
  189. $this->collectionEnvelope => $models,
  190. ];
  191. if ($pagination !== false) {
  192. return array_merge($result, $this->serializePagination($pagination));
  193. } else {
  194. return $result;
  195. }
  196. }
  197. }
  198. /**
  199. * Serializes a pagination into an array.
  200. * @param Pagination $pagination
  201. * @return array the array representation of the pagination
  202. * @see addPaginationHeaders()
  203. */
  204. protected function serializePagination($pagination)
  205. {
  206. return [
  207. $this->linksEnvelope => Link::serialize($pagination->getLinks(true)),
  208. $this->metaEnvelope => [
  209. 'totalCount' => $pagination->totalCount,
  210. 'pageCount' => $pagination->getPageCount(),
  211. 'currentPage' => $pagination->getPage() + 1,
  212. 'perPage' => $pagination->getPageSize(),
  213. ],
  214. ];
  215. }
  216. /**
  217. * Adds HTTP headers about the pagination to the response.
  218. * @param Pagination $pagination
  219. */
  220. protected function addPaginationHeaders($pagination)
  221. {
  222. $links = [];
  223. foreach ($pagination->getLinks(true) as $rel => $url) {
  224. $links[] = "<$url>; rel=$rel";
  225. }
  226. $this->response->getHeaders()
  227. ->set($this->totalCountHeader, $pagination->totalCount)
  228. ->set($this->pageCountHeader, $pagination->getPageCount())
  229. ->set($this->currentPageHeader, $pagination->getPage() + 1)
  230. ->set($this->perPageHeader, $pagination->pageSize)
  231. ->set('Link', implode(', ', $links));
  232. }
  233. /**
  234. * Serializes a model object.
  235. * @param Arrayable $model
  236. * @return array the array representation of the model
  237. */
  238. protected function serializeModel($model)
  239. {
  240. if ($this->request->getIsHead()) {
  241. return null;
  242. } else {
  243. list ($fields, $expand) = $this->getRequestedFields();
  244. return $model->toArray($fields, $expand);
  245. }
  246. }
  247. /**
  248. * Serializes the validation errors in a model.
  249. * @param Model $model
  250. * @return array the array representation of the errors
  251. */
  252. protected function serializeModelErrors($model)
  253. {
  254. $this->response->setStatusCode(422, 'Data Validation Failed.');
  255. $result = [];
  256. foreach ($model->getFirstErrors() as $name => $message) {
  257. $result[] = [
  258. 'field' => $name,
  259. 'message' => $message,
  260. ];
  261. }
  262. return $result;
  263. }
  264. /**
  265. * Serializes a set of models.
  266. * @param array $models
  267. * @return array the array representation of the models
  268. */
  269. protected function serializeModels(array $models)
  270. {
  271. list ($fields, $expand) = $this->getRequestedFields();
  272. foreach ($models as $i => $model) {
  273. if ($model instanceof Arrayable) {
  274. $models[$i] = $model->toArray($fields, $expand);
  275. } elseif (is_array($model)) {
  276. $models[$i] = ArrayHelper::toArray($model);
  277. }
  278. }
  279. return $models;
  280. }
  281. }