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.

Sort.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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\data;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\base\Object;
  11. use yii\helpers\Html;
  12. use yii\helpers\Inflector;
  13. use yii\web\Request;
  14. /**
  15. * Sort represents information relevant to sorting.
  16. *
  17. * When data needs to be sorted according to one or several attributes,
  18. * we can use Sort to represent the sorting information and generate
  19. * appropriate hyperlinks that can lead to sort actions.
  20. *
  21. * A typical usage example is as follows,
  22. *
  23. * ```php
  24. * function actionIndex()
  25. * {
  26. * $sort = new Sort([
  27. * 'attributes' => [
  28. * 'age',
  29. * 'name' => [
  30. * 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
  31. * 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
  32. * 'default' => SORT_DESC,
  33. * 'label' => 'Name',
  34. * ],
  35. * ],
  36. * ]);
  37. *
  38. * $models = Article::find()
  39. * ->where(['status' => 1])
  40. * ->orderBy($sort->orders)
  41. * ->all();
  42. *
  43. * return $this->render('index', [
  44. * 'models' => $models,
  45. * 'sort' => $sort,
  46. * ]);
  47. * }
  48. * ```
  49. *
  50. * View:
  51. *
  52. * ```php
  53. * // display links leading to sort actions
  54. * echo $sort->link('name') . ' | ' . $sort->link('age');
  55. *
  56. * foreach ($models as $model) {
  57. * // display $model here
  58. * }
  59. * ```
  60. *
  61. * In the above, we declare two [[attributes]] that support sorting: name and age.
  62. * We pass the sort information to the Article query so that the query results are
  63. * sorted by the orders specified by the Sort object. In the view, we show two hyperlinks
  64. * that can lead to pages with the data sorted by the corresponding attributes.
  65. *
  66. * @property array $attributeOrders Sort directions indexed by attribute names. Sort direction can be either
  67. * `SORT_ASC` for ascending order or `SORT_DESC` for descending order. This property is read-only.
  68. * @property array $orders The columns (keys) and their corresponding sort directions (values). This can be
  69. * passed to [[\yii\db\Query::orderBy()]] to construct a DB query. This property is read-only.
  70. *
  71. * @author Qiang Xue <qiang.xue@gmail.com>
  72. * @since 2.0
  73. */
  74. class Sort extends Object
  75. {
  76. /**
  77. * @var boolean whether the sorting can be applied to multiple attributes simultaneously.
  78. * Defaults to false, which means each time the data can only be sorted by one attribute.
  79. */
  80. public $enableMultiSort = false;
  81. /**
  82. * @var array list of attributes that are allowed to be sorted. Its syntax can be
  83. * described using the following example:
  84. *
  85. * ```php
  86. * [
  87. * 'age',
  88. * 'name' => [
  89. * 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
  90. * 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
  91. * 'default' => SORT_DESC,
  92. * 'label' => 'Name',
  93. * ],
  94. * ]
  95. * ```
  96. *
  97. * In the above, two attributes are declared: "age" and "name". The "age" attribute is
  98. * a simple attribute which is equivalent to the following:
  99. *
  100. * ```php
  101. * 'age' => [
  102. * 'asc' => ['age' => SORT_ASC],
  103. * 'desc' => ['age' => SORT_DESC],
  104. * 'default' => SORT_ASC,
  105. * 'label' => Inflector::camel2words('age'),
  106. * ]
  107. * ```
  108. *
  109. * The "name" attribute is a composite attribute:
  110. *
  111. * - The "name" key represents the attribute name which will appear in the URLs leading
  112. * to sort actions.
  113. * - The "asc" and "desc" elements specify how to sort by the attribute in ascending
  114. * and descending orders, respectively. Their values represent the actual columns and
  115. * the directions by which the data should be sorted by.
  116. * - The "default" element specifies by which direction the attribute should be sorted
  117. * if it is not currently sorted (the default value is ascending order).
  118. * - The "label" element specifies what label should be used when calling [[link()]] to create
  119. * a sort link. If not set, [[Inflector::camel2words()]] will be called to get a label.
  120. * Note that it will not be HTML-encoded.
  121. *
  122. * Note that if the Sort object is already created, you can only use the full format
  123. * to configure every attribute. Each attribute must include these elements: `asc` and `desc`.
  124. */
  125. public $attributes = [];
  126. /**
  127. * @var string the name of the parameter that specifies which attributes to be sorted
  128. * in which direction. Defaults to 'sort'.
  129. * @see params
  130. */
  131. public $sortParam = 'sort';
  132. /**
  133. * @var array the order that should be used when the current request does not specify any order.
  134. * The array keys are attribute names and the array values are the corresponding sort directions. For example,
  135. *
  136. * ```php
  137. * [
  138. * 'name' => SORT_ASC,
  139. * 'created_at' => SORT_DESC,
  140. * ]
  141. * ```
  142. *
  143. * @see attributeOrders
  144. */
  145. public $defaultOrder;
  146. /**
  147. * @var string the route of the controller action for displaying the sorted contents.
  148. * If not set, it means using the currently requested route.
  149. */
  150. public $route;
  151. /**
  152. * @var string the character used to separate different attributes that need to be sorted by.
  153. */
  154. public $separator = ',';
  155. /**
  156. * @var array parameters (name => value) that should be used to obtain the current sort directions
  157. * and to create new sort URLs. If not set, $_GET will be used instead.
  158. *
  159. * In order to add hash to all links use `array_merge($_GET, ['#' => 'my-hash'])`.
  160. *
  161. * The array element indexed by [[sortParam]] is considered to be the current sort directions.
  162. * If the element does not exist, the [[defaultOrder|default order]] will be used.
  163. *
  164. * @see sortParam
  165. * @see defaultOrder
  166. */
  167. public $params;
  168. /**
  169. * @var \yii\web\UrlManager the URL manager used for creating sort URLs. If not set,
  170. * the "urlManager" application component will be used.
  171. */
  172. public $urlManager;
  173. /**
  174. * Normalizes the [[attributes]] property.
  175. */
  176. public function init()
  177. {
  178. $attributes = [];
  179. foreach ($this->attributes as $name => $attribute) {
  180. if (!is_array($attribute)) {
  181. $attributes[$attribute] = [
  182. 'asc' => [$attribute => SORT_ASC],
  183. 'desc' => [$attribute => SORT_DESC],
  184. ];
  185. } elseif (!isset($attribute['asc'], $attribute['desc'])) {
  186. $attributes[$name] = array_merge([
  187. 'asc' => [$name => SORT_ASC],
  188. 'desc' => [$name => SORT_DESC],
  189. ], $attribute);
  190. } else {
  191. $attributes[$name] = $attribute;
  192. }
  193. }
  194. $this->attributes = $attributes;
  195. }
  196. /**
  197. * Returns the columns and their corresponding sort directions.
  198. * @param boolean $recalculate whether to recalculate the sort directions
  199. * @return array the columns (keys) and their corresponding sort directions (values).
  200. * This can be passed to [[\yii\db\Query::orderBy()]] to construct a DB query.
  201. */
  202. public function getOrders($recalculate = false)
  203. {
  204. $attributeOrders = $this->getAttributeOrders($recalculate);
  205. $orders = [];
  206. foreach ($attributeOrders as $attribute => $direction) {
  207. $definition = $this->attributes[$attribute];
  208. $columns = $definition[$direction === SORT_ASC ? 'asc' : 'desc'];
  209. foreach ($columns as $name => $dir) {
  210. $orders[$name] = $dir;
  211. }
  212. }
  213. return $orders;
  214. }
  215. /**
  216. * @var array the currently requested sort order as computed by [[getAttributeOrders]].
  217. */
  218. private $_attributeOrders;
  219. /**
  220. * Returns the currently requested sort information.
  221. * @param boolean $recalculate whether to recalculate the sort directions
  222. * @return array sort directions indexed by attribute names.
  223. * Sort direction can be either `SORT_ASC` for ascending order or
  224. * `SORT_DESC` for descending order.
  225. */
  226. public function getAttributeOrders($recalculate = false)
  227. {
  228. if ($this->_attributeOrders === null || $recalculate) {
  229. $this->_attributeOrders = [];
  230. if (($params = $this->params) === null) {
  231. $request = Yii::$app->getRequest();
  232. $params = $request instanceof Request ? $request->getQueryParams() : [];
  233. }
  234. if (isset($params[$this->sortParam]) && is_scalar($params[$this->sortParam])) {
  235. $attributes = explode($this->separator, $params[$this->sortParam]);
  236. foreach ($attributes as $attribute) {
  237. $descending = false;
  238. if (strncmp($attribute, '-', 1) === 0) {
  239. $descending = true;
  240. $attribute = substr($attribute, 1);
  241. }
  242. if (isset($this->attributes[$attribute])) {
  243. $this->_attributeOrders[$attribute] = $descending ? SORT_DESC : SORT_ASC;
  244. if (!$this->enableMultiSort) {
  245. return $this->_attributeOrders;
  246. }
  247. }
  248. }
  249. }
  250. if (empty($this->_attributeOrders) && is_array($this->defaultOrder)) {
  251. $this->_attributeOrders = $this->defaultOrder;
  252. }
  253. }
  254. return $this->_attributeOrders;
  255. }
  256. /**
  257. * Returns the sort direction of the specified attribute in the current request.
  258. * @param string $attribute the attribute name
  259. * @return boolean|null Sort direction of the attribute. Can be either `SORT_ASC`
  260. * for ascending order or `SORT_DESC` for descending order. Null is returned
  261. * if the attribute is invalid or does not need to be sorted.
  262. */
  263. public function getAttributeOrder($attribute)
  264. {
  265. $orders = $this->getAttributeOrders();
  266. return isset($orders[$attribute]) ? $orders[$attribute] : null;
  267. }
  268. /**
  269. * Generates a hyperlink that links to the sort action to sort by the specified attribute.
  270. * Based on the sort direction, the CSS class of the generated hyperlink will be appended
  271. * with "asc" or "desc".
  272. * @param string $attribute the attribute name by which the data should be sorted by.
  273. * @param array $options additional HTML attributes for the hyperlink tag.
  274. * There is one special attribute `label` which will be used as the label of the hyperlink.
  275. * If this is not set, the label defined in [[attributes]] will be used.
  276. * If no label is defined, [[\yii\helpers\Inflector::camel2words()]] will be called to get a label.
  277. * Note that it will not be HTML-encoded.
  278. * @return string the generated hyperlink
  279. * @throws InvalidConfigException if the attribute is unknown
  280. */
  281. public function link($attribute, $options = [])
  282. {
  283. if (($direction = $this->getAttributeOrder($attribute)) !== null) {
  284. $class = $direction === SORT_DESC ? 'desc' : 'asc';
  285. if (isset($options['class'])) {
  286. $options['class'] .= ' ' . $class;
  287. } else {
  288. $options['class'] = $class;
  289. }
  290. }
  291. $url = $this->createUrl($attribute);
  292. $options['data-sort'] = $this->createSortParam($attribute);
  293. if (isset($options['label'])) {
  294. $label = $options['label'];
  295. unset($options['label']);
  296. } else {
  297. if (isset($this->attributes[$attribute]['label'])) {
  298. $label = $this->attributes[$attribute]['label'];
  299. } else {
  300. $label = Inflector::camel2words($attribute);
  301. }
  302. }
  303. return Html::a($label, $url, $options);
  304. }
  305. /**
  306. * Creates a URL for sorting the data by the specified attribute.
  307. * This method will consider the current sorting status given by [[attributeOrders]].
  308. * For example, if the current page already sorts the data by the specified attribute in ascending order,
  309. * then the URL created will lead to a page that sorts the data by the specified attribute in descending order.
  310. * @param string $attribute the attribute name
  311. * @param boolean $absolute whether to create an absolute URL. Defaults to `false`.
  312. * @return string the URL for sorting. False if the attribute is invalid.
  313. * @throws InvalidConfigException if the attribute is unknown
  314. * @see attributeOrders
  315. * @see params
  316. */
  317. public function createUrl($attribute, $absolute = false)
  318. {
  319. if (($params = $this->params) === null) {
  320. $request = Yii::$app->getRequest();
  321. $params = $request instanceof Request ? $request->getQueryParams() : [];
  322. }
  323. $params[$this->sortParam] = $this->createSortParam($attribute);
  324. $params[0] = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
  325. $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
  326. if ($absolute) {
  327. return $urlManager->createAbsoluteUrl($params);
  328. } else {
  329. return $urlManager->createUrl($params);
  330. }
  331. }
  332. /**
  333. * Creates the sort variable for the specified attribute.
  334. * The newly created sort variable can be used to create a URL that will lead to
  335. * sorting by the specified attribute.
  336. * @param string $attribute the attribute name
  337. * @return string the value of the sort variable
  338. * @throws InvalidConfigException if the specified attribute is not defined in [[attributes]]
  339. */
  340. public function createSortParam($attribute)
  341. {
  342. if (!isset($this->attributes[$attribute])) {
  343. throw new InvalidConfigException("Unknown attribute: $attribute");
  344. }
  345. $definition = $this->attributes[$attribute];
  346. $directions = $this->getAttributeOrders();
  347. if (isset($directions[$attribute])) {
  348. $direction = $directions[$attribute] === SORT_DESC ? SORT_ASC : SORT_DESC;
  349. unset($directions[$attribute]);
  350. } else {
  351. $direction = isset($definition['default']) ? $definition['default'] : SORT_ASC;
  352. }
  353. if ($this->enableMultiSort) {
  354. $directions = array_merge([$attribute => $direction], $directions);
  355. } else {
  356. $directions = [$attribute => $direction];
  357. }
  358. $sorts = [];
  359. foreach ($directions as $attribute => $direction) {
  360. $sorts[] = $direction === SORT_DESC ? '-' . $attribute : $attribute;
  361. }
  362. return implode($this->separator, $sorts);
  363. }
  364. /**
  365. * Returns a value indicating whether the sort definition supports sorting by the named attribute.
  366. * @param string $name the attribute name
  367. * @return boolean whether the sort definition supports sorting by the named attribute.
  368. */
  369. public function hasAttribute($name)
  370. {
  371. return isset($this->attributes[$name]);
  372. }
  373. }