PageRenderTime 64ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/yii/web/Sort.php

https://github.com/stefan321/yii2
PHP | 336 lines | 121 code | 20 blank | 195 comment | 21 complexity | 063dbf635dec323bc250f3ce068f0945 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0
  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\web;
  8. use Yii;
  9. use yii\helpers\Html;
  10. /**
  11. * Sort represents information relevant to sorting.
  12. *
  13. * When data needs to be sorted according to one or several attributes,
  14. * we can use Sort to represent the sorting information and generate
  15. * appropriate hyperlinks that can lead to sort actions.
  16. *
  17. * A typical usage example is as follows,
  18. *
  19. * ~~~
  20. * function actionIndex()
  21. * {
  22. * $sort = new Sort(array(
  23. * 'attributes' => array(
  24. * 'age',
  25. * 'name' => array(
  26. * 'asc' => array('last_name', 'first_name'),
  27. * 'desc' => array('last_name' => true, 'first_name' => true),
  28. * ),
  29. * ),
  30. * ));
  31. *
  32. * $models = Article::find()
  33. * ->where(array('status' => 1))
  34. * ->orderBy($sort->orders)
  35. * ->all();
  36. *
  37. * $this->render('index', array(
  38. * 'models' => $models,
  39. * 'sort' => $sort,
  40. * ));
  41. * }
  42. * ~~~
  43. *
  44. * View:
  45. *
  46. * ~~~
  47. * // display links leading to sort actions
  48. * echo $sort->link('name', 'Name') . ' | ' . $sort->link('age', 'Age');
  49. *
  50. * foreach ($models as $model) {
  51. * // display $model here
  52. * }
  53. * ~~~
  54. *
  55. * In the above, we declare two [[attributes]] that support sorting: name and age.
  56. * We pass the sort information to the Article query so that the query results are
  57. * sorted by the orders specified by the Sort object. In the view, we show two hyperlinks
  58. * that can lead to pages with the data sorted by the corresponding attributes.
  59. *
  60. * @property array $orders Sort directions indexed by column names. The sort direction
  61. * can be either [[Sort::ASC]] for ascending order or [[Sort::DESC]] for descending order.
  62. * @property array $attributeOrders Sort directions indexed by attribute names. The sort
  63. * direction can be either [[Sort::ASC]] for ascending order or [[Sort::DESC]] for descending order.
  64. *
  65. * @author Qiang Xue <qiang.xue@gmail.com>
  66. * @since 2.0
  67. */
  68. class Sort extends \yii\base\Object
  69. {
  70. /**
  71. * Sort ascending
  72. */
  73. const ASC = false;
  74. /**
  75. * Sort descending
  76. */
  77. const DESC = true;
  78. /**
  79. * @var boolean whether the sorting can be applied to multiple attributes simultaneously.
  80. * Defaults to false, which means each time the data can only be sorted by one attribute.
  81. */
  82. public $enableMultiSort = false;
  83. /**
  84. * @var array list of attributes that are allowed to be sorted. Its syntax can be
  85. * described using the following example:
  86. *
  87. * ~~~
  88. * array(
  89. * 'age',
  90. * 'user' => array(
  91. * 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC),
  92. * 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC),
  93. * 'default' => 'desc',
  94. * ),
  95. * )
  96. * ~~~
  97. *
  98. * In the above, two attributes are declared: "age" and "user". The "age" attribute is
  99. * a simple attribute which is equivalent to the following:
  100. *
  101. * ~~~
  102. * 'age' => array(
  103. * 'asc' => array('age' => Sort::ASC),
  104. * 'desc' => array('age' => Sort::DESC),
  105. * )
  106. * ~~~
  107. *
  108. * The "user" attribute is a composite attribute:
  109. *
  110. * - The "user" key represents the attribute name which will appear in the URLs leading
  111. * to sort actions. Attribute names cannot contain characters listed in [[separators]].
  112. * - The "asc" and "desc" elements specify how to sort by the attribute in ascending
  113. * and descending orders, respectively. Their values represent the actual columns and
  114. * the directions by which the data should be sorted by.
  115. * - And the "default" element specifies if the attribute is not sorted currently,
  116. * in which direction it should be sorted (the default value is ascending order).
  117. */
  118. public $attributes = array();
  119. /**
  120. * @var string the name of the parameter that specifies which attributes to be sorted
  121. * in which direction. Defaults to 'sort'.
  122. * @see params
  123. */
  124. public $sortVar = 'sort';
  125. /**
  126. * @var string the tag appeared in the [[sortVar]] parameter that indicates the attribute should be sorted
  127. * in descending order. Defaults to 'desc'.
  128. */
  129. public $descTag = 'desc';
  130. /**
  131. * @var array the order that should be used when the current request does not specify any order.
  132. * The array keys are attribute names and the array values are the corresponding sort directions. For example,
  133. *
  134. * ~~~
  135. * array(
  136. * 'name' => Sort::ASC,
  137. * 'create_time' => Sort::DESC,
  138. * )
  139. * ~~~
  140. *
  141. * @see attributeOrders
  142. */
  143. public $defaults;
  144. /**
  145. * @var string the route of the controller action for displaying the sorted contents.
  146. * If not set, it means using the currently requested route.
  147. */
  148. public $route;
  149. /**
  150. * @var array separators used in the generated URL. This must be an array consisting of
  151. * two elements. The first element specifies the character separating different
  152. * attributes, while the second element specifies the character separating attribute name
  153. * and the corresponding sort direction. Defaults to `array('-', '.')`.
  154. */
  155. public $separators = array('-', '.');
  156. /**
  157. * @var array parameters (name => value) that should be used to obtain the current sort directions
  158. * and to create new sort URLs. If not set, $_GET will be used instead.
  159. *
  160. * The array element indexed by [[sortVar]] is considered to be the current sort directions.
  161. * If the element does not exist, the [[defaults|default order]] will be used.
  162. *
  163. * @see sortVar
  164. * @see defaults
  165. */
  166. public $params;
  167. /**
  168. * Returns the columns and their corresponding sort directions.
  169. * @return array the columns (keys) and their corresponding sort directions (values).
  170. * This can be passed to [[\yii\db\Query::orderBy()]] to construct a DB query.
  171. */
  172. public function getOrders()
  173. {
  174. $attributeOrders = $this->getAttributeOrders();
  175. $orders = array();
  176. foreach ($attributeOrders as $attribute => $direction) {
  177. $definition = $this->getAttribute($attribute);
  178. $columns = $definition[$direction === self::ASC ? 'asc' : 'desc'];
  179. foreach ($columns as $name => $dir) {
  180. $orders[$name] = $dir;
  181. }
  182. }
  183. return $orders;
  184. }
  185. /**
  186. * Generates a hyperlink that links to the sort action to sort by the specified attribute.
  187. * Based on the sort direction, the CSS class of the generated hyperlink will be appended
  188. * with "asc" or "desc".
  189. * @param string $attribute the attribute name by which the data should be sorted by.
  190. * @param string $label the link label. Note that the label will not be HTML-encoded.
  191. * @param array $htmlOptions additional HTML attributes for the hyperlink tag
  192. * @return string the generated hyperlink
  193. */
  194. public function link($attribute, $label, $htmlOptions = array())
  195. {
  196. if (($definition = $this->getAttribute($attribute)) === false) {
  197. return $label;
  198. }
  199. if (($direction = $this->getAttributeOrder($attribute)) !== null) {
  200. $class = $direction ? 'desc' : 'asc';
  201. if (isset($htmlOptions['class'])) {
  202. $htmlOptions['class'] .= ' ' . $class;
  203. } else {
  204. $htmlOptions['class'] = $class;
  205. }
  206. }
  207. $url = $this->createUrl($attribute);
  208. return Html::a($label, $url, $htmlOptions);
  209. }
  210. private $_attributeOrders;
  211. /**
  212. * Returns the currently requested sort information.
  213. * @param boolean $recalculate whether to recalculate the sort directions
  214. * @return array sort directions indexed by attribute names.
  215. * Sort direction can be either [[Sort::ASC]] for ascending order or
  216. * [[Sort::DESC]] for descending order.
  217. */
  218. public function getAttributeOrders($recalculate = false)
  219. {
  220. if ($this->_attributeOrders === null || $recalculate) {
  221. $this->_attributeOrders = array();
  222. $params = $this->params === null ? $_GET : $this->params;
  223. if (isset($params[$this->sortVar]) && is_scalar($params[$this->sortVar])) {
  224. $attributes = explode($this->separators[0], $params[$this->sortVar]);
  225. foreach ($attributes as $attribute) {
  226. $descending = false;
  227. if (($pos = strrpos($attribute, $this->separators[1])) !== false) {
  228. if ($descending = (substr($attribute, $pos + 1) === $this->descTag)) {
  229. $attribute = substr($attribute, 0, $pos);
  230. }
  231. }
  232. if (($this->getAttribute($attribute)) !== false) {
  233. $this->_attributeOrders[$attribute] = $descending;
  234. if (!$this->enableMultiSort) {
  235. return $this->_attributeOrders;
  236. }
  237. }
  238. }
  239. }
  240. if (empty($this->_attributeOrders) && is_array($this->defaults)) {
  241. $this->_attributeOrders = $this->defaults;
  242. }
  243. }
  244. return $this->_attributeOrders;
  245. }
  246. /**
  247. * Returns the sort direction of the specified attribute in the current request.
  248. * @param string $attribute the attribute name
  249. * @return boolean|null Sort direction of the attribute. Can be either [[Sort::ASC]]
  250. * for ascending order or [[Sort::DESC]] for descending order. Null is returned
  251. * if the attribute is invalid or does not need to be sorted.
  252. */
  253. public function getAttributeOrder($attribute)
  254. {
  255. $this->getAttributeOrders();
  256. return isset($this->_attributeOrders[$attribute]) ? $this->_attributeOrders[$attribute] : null;
  257. }
  258. /**
  259. * Creates a URL for sorting the data by the specified attribute.
  260. * This method will consider the current sorting status given by [[attributeOrders]].
  261. * For example, if the current page already sorts the data by the specified attribute in ascending order,
  262. * then the URL created will lead to a page that sorts the data by the specified attribute in descending order.
  263. * @param string $attribute the attribute name
  264. * @return string|boolean the URL for sorting. False if the attribute is invalid.
  265. * @see attributeOrders
  266. * @see params
  267. */
  268. public function createUrl($attribute)
  269. {
  270. if (($definition = $this->getAttribute($attribute)) === false) {
  271. return false;
  272. }
  273. $directions = $this->getAttributeOrders();
  274. if (isset($directions[$attribute])) {
  275. $descending = !$directions[$attribute];
  276. unset($directions[$attribute]);
  277. } elseif (isset($definition['default'])) {
  278. $descending = $definition['default'] === 'desc';
  279. } else {
  280. $descending = false;
  281. }
  282. if ($this->enableMultiSort) {
  283. $directions = array_merge(array($attribute => $descending), $directions);
  284. } else {
  285. $directions = array($attribute => $descending);
  286. }
  287. $sorts = array();
  288. foreach ($directions as $attribute => $descending) {
  289. $sorts[] = $descending ? $attribute . $this->separators[1] . $this->descTag : $attribute;
  290. }
  291. $params = $this->params === null ? $_GET : $this->params;
  292. $params[$this->sortVar] = implode($this->separators[0], $sorts);
  293. $route = $this->route === null ? Yii::$app->controller->route : $this->route;
  294. return Yii::$app->getUrlManager()->createUrl($route, $params);
  295. }
  296. /**
  297. * Returns the attribute definition of the specified name.
  298. * @param string $name the attribute name
  299. * @return array|boolean the sort definition (column names => sort directions).
  300. * False is returned if the attribute cannot be sorted.
  301. * @see attributes
  302. */
  303. public function getAttribute($name)
  304. {
  305. if (isset($this->attributes[$name])) {
  306. return $this->attributes[$name];
  307. } elseif (in_array($name, $this->attributes, true)) {
  308. return array(
  309. 'asc' => array($name => self::ASC),
  310. 'desc' => array($name => self::DESC),
  311. );
  312. } else {
  313. return false;
  314. }
  315. }
  316. }