Sort.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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\BaseObject;
  10. use yii\base\InvalidConfigException;
  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. * public 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. * For more details and usage information on Sort, see the [guide article on sorting](guide:output-sorting).
  67. *
  68. * @property array $attributeOrders Sort directions indexed by attribute names. Sort direction can be either
  69. * `SORT_ASC` for ascending order or `SORT_DESC` for descending order. Note that the type of this property
  70. * differs in getter and setter. See [[getAttributeOrders()]] and [[setAttributeOrders()]] for details.
  71. * @property array $orders The columns (keys) and their corresponding sort directions (values). This can be
  72. * passed to [[\yii\db\Query::orderBy()]] to construct a DB query. This property is read-only.
  73. *
  74. * @author Qiang Xue <qiang.xue@gmail.com>
  75. * @since 2.0
  76. */
  77. class Sort extends BaseObject
  78. {
  79. /**
  80. * @var bool whether the sorting can be applied to multiple attributes simultaneously.
  81. * Defaults to `false`, which means each time the data can only be sorted by one attribute.
  82. */
  83. public $enableMultiSort = false;
  84. /**
  85. * @var array list of attributes that are allowed to be sorted. Its syntax can be
  86. * described using the following example:
  87. *
  88. * ```php
  89. * [
  90. * 'age',
  91. * 'name' => [
  92. * 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
  93. * 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
  94. * 'default' => SORT_DESC,
  95. * 'label' => 'Name',
  96. * ],
  97. * ]
  98. * ```
  99. *
  100. * In the above, two attributes are declared: `age` and `name`. The `age` attribute is
  101. * a simple attribute which is equivalent to the following:
  102. *
  103. * ```php
  104. * 'age' => [
  105. * 'asc' => ['age' => SORT_ASC],
  106. * 'desc' => ['age' => SORT_DESC],
  107. * 'default' => SORT_ASC,
  108. * 'label' => Inflector::camel2words('age'),
  109. * ]
  110. * ```
  111. *
  112. * Since 2.0.12 particular sort direction can be also specified as direct sort expression, like following:
  113. *
  114. * ```php
  115. * 'name' => [
  116. * 'asc' => '[[last_name]] ASC NULLS FIRST', // PostgreSQL specific feature
  117. * 'desc' => '[[last_name]] DESC NULLS LAST',
  118. * ]
  119. * ```
  120. *
  121. * The `name` attribute is a composite attribute:
  122. *
  123. * - The `name` key represents the attribute name which will appear in the URLs leading
  124. * to sort actions.
  125. * - The `asc` and `desc` elements specify how to sort by the attribute in ascending
  126. * and descending orders, respectively. Their values represent the actual columns and
  127. * the directions by which the data should be sorted by.
  128. * - The `default` element specifies by which direction the attribute should be sorted
  129. * if it is not currently sorted (the default value is ascending order).
  130. * - The `label` element specifies what label should be used when calling [[link()]] to create
  131. * a sort link. If not set, [[Inflector::camel2words()]] will be called to get a label.
  132. * Note that it will not be HTML-encoded.
  133. *
  134. * Note that if the Sort object is already created, you can only use the full format
  135. * to configure every attribute. Each attribute must include these elements: `asc` and `desc`.
  136. */
  137. public $attributes = [];
  138. /**
  139. * @var string the name of the parameter that specifies which attributes to be sorted
  140. * in which direction. Defaults to `sort`.
  141. * @see params
  142. */
  143. public $sortParam = 'sort';
  144. /**
  145. * @var array the order that should be used when the current request does not specify any order.
  146. * The array keys are attribute names and the array values are the corresponding sort directions. For example,
  147. *
  148. * ```php
  149. * [
  150. * 'name' => SORT_ASC,
  151. * 'created_at' => SORT_DESC,
  152. * ]
  153. * ```
  154. *
  155. * @see attributeOrders
  156. */
  157. public $defaultOrder;
  158. /**
  159. * @var string the route of the controller action for displaying the sorted contents.
  160. * If not set, it means using the currently requested route.
  161. */
  162. public $route;
  163. /**
  164. * @var string the character used to separate different attributes that need to be sorted by.
  165. */
  166. public $separator = ',';
  167. /**
  168. * @var array parameters (name => value) that should be used to obtain the current sort directions
  169. * and to create new sort URLs. If not set, `$_GET` will be used instead.
  170. *
  171. * In order to add hash to all links use `array_merge($_GET, ['#' => 'my-hash'])`.
  172. *
  173. * The array element indexed by [[sortParam]] is considered to be the current sort directions.
  174. * If the element does not exist, the [[defaultOrder|default order]] will be used.
  175. *
  176. * @see sortParam
  177. * @see defaultOrder
  178. */
  179. public $params;
  180. /**
  181. * @var \yii\web\UrlManager the URL manager used for creating sort URLs. If not set,
  182. * the `urlManager` application component will be used.
  183. */
  184. public $urlManager;
  185. /**
  186. * Normalizes the [[attributes]] property.
  187. */
  188. public function init()
  189. {
  190. $attributes = [];
  191. foreach ($this->attributes as $name => $attribute) {
  192. if (!is_array($attribute)) {
  193. $attributes[$attribute] = [
  194. 'asc' => [$attribute => SORT_ASC],
  195. 'desc' => [$attribute => SORT_DESC],
  196. ];
  197. } elseif (!isset($attribute['asc'], $attribute['desc'])) {
  198. $attributes[$name] = array_merge([
  199. 'asc' => [$name => SORT_ASC],
  200. 'desc' => [$name => SORT_DESC],
  201. ], $attribute);
  202. } else {
  203. $attributes[$name] = $attribute;
  204. }
  205. }
  206. $this->attributes = $attributes;
  207. }
  208. /**
  209. * Returns the columns and their corresponding sort directions.
  210. * @param bool $recalculate whether to recalculate the sort directions
  211. * @return array the columns (keys) and their corresponding sort directions (values).
  212. * This can be passed to [[\yii\db\Query::orderBy()]] to construct a DB query.
  213. */
  214. public function getOrders($recalculate = false)
  215. {
  216. $attributeOrders = $this->getAttributeOrders($recalculate);
  217. $orders = [];
  218. foreach ($attributeOrders as $attribute => $direction) {
  219. $definition = $this->attributes[$attribute];
  220. $columns = $definition[$direction === SORT_ASC ? 'asc' : 'desc'];
  221. if (is_array($columns) || $columns instanceof \Traversable) {
  222. foreach ($columns as $name => $dir) {
  223. $orders[$name] = $dir;
  224. }
  225. } else {
  226. $orders[] = $columns;
  227. }
  228. }
  229. return $orders;
  230. }
  231. /**
  232. * @var array the currently requested sort order as computed by [[getAttributeOrders]].
  233. */
  234. private $_attributeOrders;
  235. /**
  236. * Returns the currently requested sort information.
  237. * @param bool $recalculate whether to recalculate the sort directions
  238. * @return array sort directions indexed by attribute names.
  239. * Sort direction can be either `SORT_ASC` for ascending order or
  240. * `SORT_DESC` for descending order.
  241. */
  242. public function getAttributeOrders($recalculate = false)
  243. {
  244. if ($this->_attributeOrders === null || $recalculate) {
  245. $this->_attributeOrders = [];
  246. if (($params = $this->params) === null) {
  247. $request = Yii::$app->getRequest();
  248. $params = $request instanceof Request ? $request->getQueryParams() : [];
  249. }
  250. if (isset($params[$this->sortParam])) {
  251. foreach ($this->parseSortParam($params[$this->sortParam]) as $attribute) {
  252. $descending = false;
  253. if (strncmp($attribute, '-', 1) === 0) {
  254. $descending = true;
  255. $attribute = substr($attribute, 1);
  256. }
  257. if (isset($this->attributes[$attribute])) {
  258. $this->_attributeOrders[$attribute] = $descending ? SORT_DESC : SORT_ASC;
  259. if (!$this->enableMultiSort) {
  260. return $this->_attributeOrders;
  261. }
  262. }
  263. }
  264. }
  265. if (empty($this->_attributeOrders) && is_array($this->defaultOrder)) {
  266. $this->_attributeOrders = $this->defaultOrder;
  267. }
  268. }
  269. return $this->_attributeOrders;
  270. }
  271. /**
  272. * Parses the value of [[sortParam]] into an array of sort attributes.
  273. *
  274. * The format must be the attribute name only for ascending
  275. * or the attribute name prefixed with `-` for descending.
  276. *
  277. * For example the following return value will result in ascending sort by
  278. * `category` and descending sort by `created_at`:
  279. *
  280. * ```php
  281. * [
  282. * 'category',
  283. * '-created_at'
  284. * ]
  285. * ```
  286. *
  287. * @param string $param the value of the [[sortParam]].
  288. * @return array the valid sort attributes.
  289. * @since 2.0.12
  290. * @see $separator for the attribute name separator.
  291. * @see $sortParam
  292. */
  293. protected function parseSortParam($param)
  294. {
  295. return is_scalar($param) ? explode($this->separator, $param) : [];
  296. }
  297. /**
  298. * Sets up the currently sort information.
  299. * @param array|null $attributeOrders sort directions indexed by attribute names.
  300. * Sort direction can be either `SORT_ASC` for ascending order or
  301. * `SORT_DESC` for descending order.
  302. * @param bool $validate whether to validate given attribute orders against [[attributes]] and [[enableMultiSort]].
  303. * If validation is enabled incorrect entries will be removed.
  304. * @since 2.0.10
  305. */
  306. public function setAttributeOrders($attributeOrders, $validate = true)
  307. {
  308. if ($attributeOrders === null || !$validate) {
  309. $this->_attributeOrders = $attributeOrders;
  310. } else {
  311. $this->_attributeOrders = [];
  312. foreach ($attributeOrders as $attribute => $order) {
  313. if (isset($this->attributes[$attribute])) {
  314. $this->_attributeOrders[$attribute] = $order;
  315. if (!$this->enableMultiSort) {
  316. break;
  317. }
  318. }
  319. }
  320. }
  321. }
  322. /**
  323. * Returns the sort direction of the specified attribute in the current request.
  324. * @param string $attribute the attribute name
  325. * @return bool|null Sort direction of the attribute. Can be either `SORT_ASC`
  326. * for ascending order or `SORT_DESC` for descending order. Null is returned
  327. * if the attribute is invalid or does not need to be sorted.
  328. */
  329. public function getAttributeOrder($attribute)
  330. {
  331. $orders = $this->getAttributeOrders();
  332. return isset($orders[$attribute]) ? $orders[$attribute] : null;
  333. }
  334. /**
  335. * Generates a hyperlink that links to the sort action to sort by the specified attribute.
  336. * Based on the sort direction, the CSS class of the generated hyperlink will be appended
  337. * with "asc" or "desc".
  338. * @param string $attribute the attribute name by which the data should be sorted by.
  339. * @param array $options additional HTML attributes for the hyperlink tag.
  340. * There is one special attribute `label` which will be used as the label of the hyperlink.
  341. * If this is not set, the label defined in [[attributes]] will be used.
  342. * If no label is defined, [[\yii\helpers\Inflector::camel2words()]] will be called to get a label.
  343. * Note that it will not be HTML-encoded.
  344. * @return string the generated hyperlink
  345. * @throws InvalidConfigException if the attribute is unknown
  346. */
  347. public function link($attribute, $options = [])
  348. {
  349. if (($direction = $this->getAttributeOrder($attribute)) !== null) {
  350. $class = $direction === SORT_DESC ? 'desc' : 'asc';
  351. if (isset($options['class'])) {
  352. $options['class'] .= ' ' . $class;
  353. } else {
  354. $options['class'] = $class;
  355. }
  356. }
  357. $url = $this->createUrl($attribute);
  358. $options['data-sort'] = $this->createSortParam($attribute);
  359. if (isset($options['label'])) {
  360. $label = $options['label'];
  361. unset($options['label']);
  362. } else {
  363. if (isset($this->attributes[$attribute]['label'])) {
  364. $label = $this->attributes[$attribute]['label'];
  365. } else {
  366. $label = Inflector::camel2words($attribute);
  367. }
  368. }
  369. return Html::a($label, $url, $options);
  370. }
  371. /**
  372. * Creates a URL for sorting the data by the specified attribute.
  373. * This method will consider the current sorting status given by [[attributeOrders]].
  374. * For example, if the current page already sorts the data by the specified attribute in ascending order,
  375. * then the URL created will lead to a page that sorts the data by the specified attribute in descending order.
  376. * @param string $attribute the attribute name
  377. * @param bool $absolute whether to create an absolute URL. Defaults to `false`.
  378. * @return string the URL for sorting. False if the attribute is invalid.
  379. * @throws InvalidConfigException if the attribute is unknown
  380. * @see attributeOrders
  381. * @see params
  382. */
  383. public function createUrl($attribute, $absolute = false)
  384. {
  385. if (($params = $this->params) === null) {
  386. $request = Yii::$app->getRequest();
  387. $params = $request instanceof Request ? $request->getQueryParams() : [];
  388. }
  389. $params[$this->sortParam] = $this->createSortParam($attribute);
  390. $params[0] = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
  391. $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
  392. if ($absolute) {
  393. return $urlManager->createAbsoluteUrl($params);
  394. }
  395. return $urlManager->createUrl($params);
  396. }
  397. /**
  398. * Creates the sort variable for the specified attribute.
  399. * The newly created sort variable can be used to create a URL that will lead to
  400. * sorting by the specified attribute.
  401. * @param string $attribute the attribute name
  402. * @return string the value of the sort variable
  403. * @throws InvalidConfigException if the specified attribute is not defined in [[attributes]]
  404. */
  405. public function createSortParam($attribute)
  406. {
  407. if (!isset($this->attributes[$attribute])) {
  408. throw new InvalidConfigException("Unknown attribute: $attribute");
  409. }
  410. $definition = $this->attributes[$attribute];
  411. $directions = $this->getAttributeOrders();
  412. if (isset($directions[$attribute])) {
  413. $direction = $directions[$attribute] === SORT_DESC ? SORT_ASC : SORT_DESC;
  414. unset($directions[$attribute]);
  415. } else {
  416. $direction = isset($definition['default']) ? $definition['default'] : SORT_ASC;
  417. }
  418. if ($this->enableMultiSort) {
  419. $directions = array_merge([$attribute => $direction], $directions);
  420. } else {
  421. $directions = [$attribute => $direction];
  422. }
  423. $sorts = [];
  424. foreach ($directions as $attribute => $direction) {
  425. $sorts[] = $direction === SORT_DESC ? '-' . $attribute : $attribute;
  426. }
  427. return implode($this->separator, $sorts);
  428. }
  429. /**
  430. * Returns a value indicating whether the sort definition supports sorting by the named attribute.
  431. * @param string $name the attribute name
  432. * @return bool whether the sort definition supports sorting by the named attribute.
  433. */
  434. public function hasAttribute($name)
  435. {
  436. return isset($this->attributes[$name]);
  437. }
  438. }