Serializer.php 3.46 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\rest;

use Yii;
use yii\base\Component;
use yii\base\Model;
use yii\data\DataProviderInterface;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\Request;
use yii\web\Response;

/**
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Serializer extends Component
{
	public $fieldsParam = 'fields';
	public $expandParam = 'expand';
	public $totalCountHeader = 'X-Pagination-Total-Count';
	public $pageCountHeader = 'X-Pagination-Page-Count';
	public $currentPageHeader = 'X-Pagination-Current-Page';
	public $perPageHeader = 'X-Pagination-Per-Page';
	/**
	 * @var Request
	 */
	public $request;
	/**
	 * @var Response
	 */
	public $response;

	public function init()
	{
		if ($this->request === null) {
			$this->request = Yii::$app->getRequest();
		}
		if ($this->response === null) {
			$this->response = Yii::$app->getResponse();
		}
	}

	public function serialize($data)
	{
		if ($data instanceof Model) {
			return $data->hasErrors() ? $this->serializeModelErrors($data) : $this->serializeModel($data);
		} elseif ($data instanceof DataProviderInterface) {
			return $this->serializeDataProvider($data);
		} else {
			return $data;
		}
	}

	protected function getRequestedFields()
	{
		$fields = $this->request->get($this->fieldsParam);
		$expand = $this->request->get($this->expandParam);
		return [
			preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY),
			preg_split('/\s*,\s*/', $expand, -1, PREG_SPLIT_NO_EMPTY),
		];
	}

	/**
	 * @param DataProviderInterface $dataProvider
	 * @return array
	 */
	protected function serializeDataProvider($dataProvider)
	{
		$models = $dataProvider->getModels();

		if (($pagination = $dataProvider->getPagination()) !== false) {
			$this->addPaginationHeaders($pagination);
		}

		if ($this->request->getIsHead()) {
			return null;
		} else {
			return $this->serializeModels($models);
		}
	}

	/**
	 * @param Pagination $pagination
	 */
	protected function addPaginationHeaders($pagination)
	{
		$links = [];
		foreach ($pagination->getLinks(true) as $rel => $url) {
			$links[] = "<$url>; rel=$rel";
		}

		$this->response->getHeaders()
			->set($this->totalCountHeader, $pagination->totalCount)
			->set($this->pageCountHeader, $pagination->getPageCount())
			->set($this->currentPageHeader, $pagination->getPage() + 1)
			->set($this->perPageHeader, $pagination->pageSize)
			->set('Link', implode(', ', $links));
	}

	/**
	 * @param Model $model
	 * @return array
	 */
	protected function serializeModel($model)
	{
		if ($this->request->getIsHead()) {
			return null;
		} else {
			list ($fields, $expand) = $this->getRequestedFields();
			return $model->toArray($fields, $expand);
		}
	}

	/**
	 * @param Model $model
	 * @return array
	 */
	protected function serializeModelErrors($model)
	{
Qiang Xue committed
129
		$this->response->setStatusCode(422, 'Data Validation Failed.');
Qiang Xue committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
		$result = [];
		foreach ($model->getFirstErrors() as $name => $message) {
			$result[] = [
				'field' => $name,
				'message' => $message,
			];
		}
		return $result;
	}

	protected function serializeModels(array $models)
	{
		list ($fields, $expand) = $this->getRequestedFields();
		foreach ($models as $i => $model) {
			if ($model instanceof Model) {
				$models[$i] = $model->toArray($fields, $expand);
			} elseif (is_array($model)) {
				$models[$i] = ArrayHelper::toArray($model);
			}
		}
		return $models;
	}
}