Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

424 lines
16KB

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