Sort.php 13.4 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\data;
Qiang Xue committed
9

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\InvalidConfigException;
12
use yii\base\Object;
Qiang Xue committed
13
use yii\helpers\Html;
Qiang Xue committed
14
use yii\helpers\Inflector;
15
use yii\web\Request;
Qiang Xue committed
16

Qiang Xue committed
17
/**
Qiang Xue committed
18
 * Sort represents information relevant to sorting.
Qiang Xue committed
19 20
 *
 * When data needs to be sorted according to one or several attributes,
Qiang Xue committed
21
 * we can use Sort to represent the sorting information and generate
Qiang Xue committed
22 23
 * appropriate hyperlinks that can lead to sort actions.
 *
Qiang Xue committed
24
 * A typical usage example is as follows,
Qiang Xue committed
25 26 27 28
 *
 * ~~~
 * function actionIndex()
 * {
Alexander Makarov committed
29 30
 *     $sort = new Sort([
 *         'attributes' => [
Qiang Xue committed
31
 *             'age',
Alexander Makarov committed
32
 *             'name' => [
33 34 35
 *                 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
 *                 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
 *                 'default' => SORT_DESC,
Qiang Xue committed
36
 *                 'label' => 'Name',
Alexander Makarov committed
37 38 39
 *             ],
 *         ],
 *     ]);
Qiang Xue committed
40
 *
Qiang Xue committed
41
 *     $models = Article::find()
Alexander Makarov committed
42
 *         ->where(['status' => 1])
Qiang Xue committed
43
 *         ->orderBy($sort->orders)
Qiang Xue committed
44 45
 *         ->all();
 *
Alexander Makarov committed
46
 *     return $this->render('index', [
Qiang Xue committed
47 48
 *          'models' => $models,
 *          'sort' => $sort,
Alexander Makarov committed
49
 *     ]);
Qiang Xue committed
50 51 52 53 54 55
 * }
 * ~~~
 *
 * View:
 *
 * ~~~
Qiang Xue committed
56
 * // display links leading to sort actions
Qiang Xue committed
57
 * echo $sort->link('name') . ' | ' . $sort->link('age');
Qiang Xue committed
58
 *
resurtm committed
59
 * foreach ($models as $model) {
Qiang Xue committed
60 61 62 63
 *     // display $model here
 * }
 * ~~~
 *
Qiang Xue committed
64 65 66 67 68
 * In the above, we declare two [[attributes]] that support sorting: name and age.
 * We pass the sort information to the Article query so that the query results are
 * sorted by the orders specified by the Sort object. In the view, we show two hyperlinks
 * that can lead to pages with the data sorted by the corresponding attributes.
 *
69
 * @property array $attributeOrders Sort directions indexed by attribute names. Sort direction can be either
70
 * `SORT_ASC` for ascending order or `SORT_DESC` for descending order. This property is read-only.
71 72
 * @property array $orders The columns (keys) and their corresponding sort directions (values). This can be
 * passed to [[\yii\db\Query::orderBy()]] to construct a DB query. This property is read-only.
73
 *
Qiang Xue committed
74
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
75
 * @since 2.0
Qiang Xue committed
76
 */
77
class Sort extends Object
Qiang Xue committed
78 79 80 81 82
{
	/**
	 * @var boolean whether the sorting can be applied to multiple attributes simultaneously.
	 * Defaults to false, which means each time the data can only be sorted by one attribute.
	 */
Qiang Xue committed
83
	public $enableMultiSort = false;
Qiang Xue committed
84

Qiang Xue committed
85
	/**
Qiang Xue committed
86 87
	 * @var array list of attributes that are allowed to be sorted. Its syntax can be
	 * described using the following example:
Qiang Xue committed
88
	 *
Qiang Xue committed
89
	 * ~~~
Alexander Makarov committed
90
	 * [
Qiang Xue committed
91
	 *     'age',
Alexander Makarov committed
92
	 *     'name' => [
93 94 95
	 *         'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
	 *         'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
	 *         'default' => SORT_DESC,
Qiang Xue committed
96
	 *         'label' => 'Name',
Alexander Makarov committed
97 98
	 *     ],
	 * ]
Qiang Xue committed
99
	 * ~~~
Qiang Xue committed
100
	 *
101
	 * In the above, two attributes are declared: "age" and "name". The "age" attribute is
Qiang Xue committed
102
	 * a simple attribute which is equivalent to the following:
Qiang Xue committed
103
	 *
Qiang Xue committed
104
	 * ~~~
Alexander Makarov committed
105
	 * 'age' => [
106 107 108
	 *     'asc' => ['age' => SORT_ASC],
	 *     'desc' => ['age' => SORT_DESC],
	 *     'default' => SORT_ASC,
Qiang Xue committed
109
	 *     'label' => Inflector::camel2words('age'),
Alexander Makarov committed
110
	 * ]
Qiang Xue committed
111
	 * ~~~
Qiang Xue committed
112
	 *
113
	 * The "name" attribute is a composite attribute:
Qiang Xue committed
114
	 *
115 116
	 * - The "name" key represents the attribute name which will appear in the URLs leading
	 *   to sort actions.
Qiang Xue committed
117 118 119
	 * - The "asc" and "desc" elements specify how to sort by the attribute in ascending
	 *   and descending orders, respectively. Their values represent the actual columns and
	 *   the directions by which the data should be sorted by.
Qiang Xue committed
120 121 122 123
	 * - The "default" element specifies by which direction the attribute should be sorted
	 *   if it is not currently sorted (the default value is ascending order).
	 * - The "label" element specifies what label should be used when calling [[link()]] to create
	 *   a sort link. If not set, [[Inflector::camel2words()]] will be called to get a label.
124
	 *   Note that it will not be HTML-encoded.
Qiang Xue committed
125 126
	 *
	 * Note that if the Sort object is already created, you can only use the full format
127
	 * to configure every attribute. Each attribute must include these elements: `asc` and `desc`.
Qiang Xue committed
128
	 */
Alexander Makarov committed
129
	public $attributes = [];
Qiang Xue committed
130
	/**
Qiang Xue committed
131
	 * @var string the name of the parameter that specifies which attributes to be sorted
Qiang Xue committed
132
	 * in which direction. Defaults to 'sort'.
Qiang Xue committed
133
	 * @see params
Qiang Xue committed
134
	 */
135
	public $sortParam = 'sort';
Qiang Xue committed
136
	/**
Qiang Xue committed
137 138
	 * @var array the order that should be used when the current request does not specify any order.
	 * The array keys are attribute names and the array values are the corresponding sort directions. For example,
Qiang Xue committed
139
	 *
Qiang Xue committed
140
	 * ~~~
Alexander Makarov committed
141
	 * [
142
	 *     'name' => SORT_ASC,
Alexander Kochetov committed
143
	 *     'created_at' => SORT_DESC,
Alexander Makarov committed
144
	 * ]
Qiang Xue committed
145
	 * ~~~
Qiang Xue committed
146
	 *
Qiang Xue committed
147
	 * @see attributeOrders
Qiang Xue committed
148
	 */
Qiang Xue committed
149
	public $defaultOrder;
Qiang Xue committed
150
	/**
Qiang Xue committed
151 152
	 * @var string the route of the controller action for displaying the sorted contents.
	 * If not set, it means using the currently requested route.
Qiang Xue committed
153
	 */
Qiang Xue committed
154
	public $route;
Qiang Xue committed
155
	/**
156
	 * @var string the character used to separate different attributes that need to be sorted by.
Qiang Xue committed
157
	 */
158
	public $separator = ',';
Qiang Xue committed
159
	/**
Qiang Xue committed
160
	 * @var array parameters (name => value) that should be used to obtain the current sort directions
Qiang Xue committed
161 162
	 * and to create new sort URLs. If not set, $_GET will be used instead.
	 *
163 164
	 * In order to add hash to all links use `array_merge($_GET, ['#' => 'my-hash'])`.
	 *
165
	 * The array element indexed by [[sortParam]] is considered to be the current sort directions.
166
	 * If the element does not exist, the [[defaultOrder|default order]] will be used.
Qiang Xue committed
167
	 *
168
	 * @see sortParam
Qiang Xue committed
169
	 * @see defaultOrder
Qiang Xue committed
170 171
	 */
	public $params;
Qiang Xue committed
172 173 174 175 176
	/**
	 * @var \yii\web\UrlManager the URL manager used for creating sort URLs. If not set,
	 * the "urlManager" application component will be used.
	 */
	public $urlManager;
Qiang Xue committed
177

Qiang Xue committed
178 179 180 181 182
	/**
	 * Normalizes the [[attributes]] property.
	 */
	public function init()
	{
Alexander Makarov committed
183
		$attributes = [];
Qiang Xue committed
184
		foreach ($this->attributes as $name => $attribute) {
Qiang Xue committed
185
			if (!is_array($attribute)) {
Alexander Makarov committed
186
				$attributes[$attribute] = [
187 188
					'asc' => [$attribute => SORT_ASC],
					'desc' => [$attribute => SORT_DESC],
Alexander Makarov committed
189
				];
190
			} elseif (!isset($attribute['asc'], $attribute['desc'])) {
Alexander Makarov committed
191
				$attributes[$name] = array_merge([
192 193
					'asc' => [$name => SORT_ASC],
					'desc' => [$name => SORT_DESC],
Alexander Makarov committed
194
				], $attribute);
195 196
			} else {
				$attributes[$name] = $attribute;
Qiang Xue committed
197 198 199 200 201
			}
		}
		$this->attributes = $attributes;
	}

Qiang Xue committed
202
	/**
Qiang Xue committed
203
	 * Returns the columns and their corresponding sort directions.
Qiang Xue committed
204
	 * @param boolean $recalculate whether to recalculate the sort directions
Qiang Xue committed
205 206
	 * @return array the columns (keys) and their corresponding sort directions (values).
	 * This can be passed to [[\yii\db\Query::orderBy()]] to construct a DB query.
Qiang Xue committed
207
	 */
Qiang Xue committed
208
	public function getOrders($recalculate = false)
Qiang Xue committed
209
	{
Qiang Xue committed
210
		$attributeOrders = $this->getAttributeOrders($recalculate);
Alexander Makarov committed
211
		$orders = [];
Qiang Xue committed
212
		foreach ($attributeOrders as $attribute => $direction) {
Qiang Xue committed
213
			$definition = $this->attributes[$attribute];
214
			$columns = $definition[$direction === SORT_ASC ? 'asc' : 'desc'];
Qiang Xue committed
215 216
			foreach ($columns as $name => $dir) {
				$orders[$name] = $dir;
Qiang Xue committed
217 218
			}
		}
Qiang Xue committed
219
		return $orders;
Qiang Xue committed
220 221
	}

222 223 224
	/**
	 * @var array the currently requested sort order as computed by [[getAttributeOrders]].
	 */
Qiang Xue committed
225 226
	private $_attributeOrders;

Qiang Xue committed
227 228
	/**
	 * Returns the currently requested sort information.
Qiang Xue committed
229
	 * @param boolean $recalculate whether to recalculate the sort directions
Qiang Xue committed
230
	 * @return array sort directions indexed by attribute names.
231 232
	 * Sort direction can be either `SORT_ASC` for ascending order or
	 * `SORT_DESC` for descending order.
Qiang Xue committed
233
	 */
Qiang Xue committed
234
	public function getAttributeOrders($recalculate = false)
Qiang Xue committed
235
	{
Qiang Xue committed
236
		if ($this->_attributeOrders === null || $recalculate) {
Alexander Makarov committed
237
			$this->_attributeOrders = [];
238 239
			if (($params = $this->params) === null) {
				$request = Yii::$app->getRequest();
240
				$params = $request instanceof Request ? $request->getQueryParams() : [];
241
			}
242 243
			if (isset($params[$this->sortParam]) && is_scalar($params[$this->sortParam])) {
				$attributes = explode($this->separator, $params[$this->sortParam]);
Qiang Xue committed
244
				foreach ($attributes as $attribute) {
Qiang Xue committed
245
					$descending = false;
246 247 248
					if (strncmp($attribute, '-', 1) === 0) {
						$descending = true;
						$attribute = substr($attribute, 1);
Qiang Xue committed
249 250
					}

Qiang Xue committed
251
					if (isset($this->attributes[$attribute])) {
252
						$this->_attributeOrders[$attribute] = $descending ? SORT_DESC : SORT_ASC;
Qiang Xue committed
253
						if (!$this->enableMultiSort) {
Qiang Xue committed
254
							return $this->_attributeOrders;
Qiang Xue committed
255
						}
Qiang Xue committed
256 257 258
					}
				}
			}
Qiang Xue committed
259 260
			if (empty($this->_attributeOrders) && is_array($this->defaultOrder)) {
				$this->_attributeOrders = $this->defaultOrder;
Qiang Xue committed
261
			}
Qiang Xue committed
262
		}
Qiang Xue committed
263
		return $this->_attributeOrders;
Qiang Xue committed
264 265 266 267 268
	}

	/**
	 * Returns the sort direction of the specified attribute in the current request.
	 * @param string $attribute the attribute name
269 270
	 * @return boolean|null Sort direction of the attribute. Can be either `SORT_ASC`
	 * for ascending order or `SORT_DESC` for descending order. Null is returned
Qiang Xue committed
271
	 * if the attribute is invalid or does not need to be sorted.
Qiang Xue committed
272
	 */
Qiang Xue committed
273
	public function getAttributeOrder($attribute)
Qiang Xue committed
274
	{
Qiang Xue committed
275 276
		$orders = $this->getAttributeOrders();
		return isset($orders[$attribute]) ? $orders[$attribute] : null;
Qiang Xue committed
277 278
	}

Qiang Xue committed
279 280 281 282 283
	/**
	 * Generates a hyperlink that links to the sort action to sort by the specified attribute.
	 * Based on the sort direction, the CSS class of the generated hyperlink will be appended
	 * with "asc" or "desc".
	 * @param string $attribute the attribute name by which the data should be sorted by.
284 285 286
	 * @param array $options additional HTML attributes for the hyperlink tag.
	 * There is one special attribute `label` which will be used as the label of the hyperlink.
	 * If this is not set, the label defined in [[attributes]] will be used.
287
	 * If no label is defined, [[\yii\helpers\Inflector::camel2words()]] will be called to get a label.
288
	 * Note that it will not be HTML-encoded.
Qiang Xue committed
289 290 291
	 * @return string the generated hyperlink
	 * @throws InvalidConfigException if the attribute is unknown
	 */
Alexander Makarov committed
292
	public function link($attribute, $options = [])
Qiang Xue committed
293 294
	{
		if (($direction = $this->getAttributeOrder($attribute)) !== null) {
295
			$class = $direction === SORT_DESC ? 'desc' : 'asc';
Qiang Xue committed
296 297 298 299 300 301 302 303
			if (isset($options['class'])) {
				$options['class'] .= ' ' . $class;
			} else {
				$options['class'] = $class;
			}
		}

		$url = $this->createUrl($attribute);
304
		$options['data-sort'] = $this->createSortParam($attribute);
305

306 307 308 309
		if (isset($options['label'])) {
			$label = $options['label'];
			unset($options['label']);
		} else {
310 311 312 313 314
			if (isset($this->attributes[$attribute]['label'])) {
				$label = $this->attributes[$attribute]['label'];
			} else {
				$label = Inflector::camel2words($attribute);
			}
315 316
		}
		return Html::a($label, $url, $options);
Qiang Xue committed
317 318
	}

Qiang Xue committed
319
	/**
Qiang Xue committed
320
	 * Creates a URL for sorting the data by the specified attribute.
Qiang Xue committed
321
	 * This method will consider the current sorting status given by [[attributeOrders]].
Qiang Xue committed
322 323 324
	 * For example, if the current page already sorts the data by the specified attribute in ascending order,
	 * then the URL created will lead to a page that sorts the data by the specified attribute in descending order.
	 * @param string $attribute the attribute name
325
	 * @param boolean $absolute whether to create an absolute URL. Defaults to `false`.
Qiang Xue committed
326 327
	 * @return string the URL for sorting. False if the attribute is invalid.
	 * @throws InvalidConfigException if the attribute is unknown
Qiang Xue committed
328
	 * @see attributeOrders
Qiang Xue committed
329
	 * @see params
Qiang Xue committed
330
	 */
331
	public function createUrl($attribute, $absolute = false)
Qiang Xue committed
332
	{
333 334
		if (($params = $this->params) === null) {
			$request = Yii::$app->getRequest();
335
			$params = $request instanceof Request ? $request->getQueryParams() : [];
336
		}
337
		$params[$this->sortParam] = $this->createSortParam($attribute);
338
		$params[0] = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
Qiang Xue committed
339
		$urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
340
		if ($absolute) {
341
			return $urlManager->createAbsoluteUrl($params);
342
		} else {
343
			return $urlManager->createUrl($params);
344
		}
Qiang Xue committed
345 346 347 348 349 350 351 352 353 354
	}

	/**
	 * Creates the sort variable for the specified attribute.
	 * The newly created sort variable can be used to create a URL that will lead to
	 * sorting by the specified attribute.
	 * @param string $attribute the attribute name
	 * @return string the value of the sort variable
	 * @throws InvalidConfigException if the specified attribute is not defined in [[attributes]]
	 */
355
	public function createSortParam($attribute)
Qiang Xue committed
356
	{
Qiang Xue committed
357
		if (!isset($this->attributes[$attribute])) {
Qiang Xue committed
358
			throw new InvalidConfigException("Unknown attribute: $attribute");
Qiang Xue committed
359
		}
Qiang Xue committed
360
		$definition = $this->attributes[$attribute];
Qiang Xue committed
361
		$directions = $this->getAttributeOrders();
Qiang Xue committed
362
		if (isset($directions[$attribute])) {
Qiang Xue committed
363
			$direction = $directions[$attribute] === SORT_DESC ? SORT_ASC : SORT_DESC;
Qiang Xue committed
364 365
			unset($directions[$attribute]);
		} else {
Qiang Xue committed
366
			$direction = isset($definition['default']) ? $definition['default'] : SORT_ASC;
Qiang Xue committed
367 368 369
		}

		if ($this->enableMultiSort) {
Qiang Xue committed
370
			$directions = array_merge([$attribute => $direction], $directions);
Qiang Xue committed
371
		} else {
Qiang Xue committed
372
			$directions = [$attribute => $direction];
Qiang Xue committed
373 374
		}

Alexander Makarov committed
375
		$sorts = [];
Qiang Xue committed
376
		foreach ($directions as $attribute => $direction) {
377
			$sorts[] = $direction === SORT_DESC ? '-' . $attribute : $attribute;
Qiang Xue committed
378
		}
379
		return implode($this->separator, $sorts);
Qiang Xue committed
380
	}
Qiang Xue committed
381 382 383 384 385 386 387 388 389 390

	/**
	 * Returns a value indicating whether the sort definition supports sorting by the named attribute.
	 * @param string $name the attribute name
	 * @return boolean whether the sort definition supports sorting by the named attribute.
	 */
	public function hasAttribute($name)
	{
		return isset($this->attributes[$name]);
	}
Zander Baldwin committed
391
}