Sort.php 13.5 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;
Qiang Xue committed
15

Qiang Xue committed
16
/**
Qiang Xue committed
17
 * Sort represents information relevant to sorting.
Qiang Xue committed
18 19
 *
 * When data needs to be sorted according to one or several attributes,
Qiang Xue committed
20
 * we can use Sort to represent the sorting information and generate
Qiang Xue committed
21 22
 * appropriate hyperlinks that can lead to sort actions.
 *
Qiang Xue committed
23
 * A typical usage example is as follows,
Qiang Xue committed
24 25 26 27
 *
 * ~~~
 * function actionIndex()
 * {
Alexander Makarov committed
28 29
 *     $sort = new Sort([
 *         'attributes' => [
Qiang Xue committed
30
 *             'age',
Alexander Makarov committed
31 32 33
 *             'name' => [
 *                 'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC],
 *                 'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC],
Qiang Xue committed
34 35
 *                 'default' => Sort::DESC,
 *                 'label' => 'Name',
Alexander Makarov committed
36 37 38
 *             ],
 *         ],
 *     ]);
Qiang Xue committed
39
 *
Qiang Xue committed
40
 *     $models = Article::find()
Alexander Makarov committed
41
 *         ->where(['status' => 1])
Qiang Xue committed
42
 *         ->orderBy($sort->orders)
Qiang Xue committed
43 44
 *         ->all();
 *
Alexander Makarov committed
45
 *     return $this->render('index', [
Qiang Xue committed
46 47
 *          'models' => $models,
 *          'sort' => $sort,
Alexander Makarov committed
48
 *     ]);
Qiang Xue committed
49 50 51 52 53 54
 * }
 * ~~~
 *
 * View:
 *
 * ~~~
Qiang Xue committed
55
 * // display links leading to sort actions
Qiang Xue committed
56
 * echo $sort->link('name') . ' | ' . $sort->link('age');
Qiang Xue committed
57
 *
resurtm committed
58
 * foreach ($models as $model) {
Qiang Xue committed
59 60 61 62
 *     // display $model here
 * }
 * ~~~
 *
Qiang Xue committed
63 64 65 66 67
 * 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.
 *
68 69 70 71
 * @property array $attributeOrders Sort directions indexed by attribute names. Sort direction can be either
 * [[Sort::ASC]] for ascending order or [[Sort::DESC]] for descending order. This property is read-only.
 * @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.
72
 *
Qiang Xue committed
73
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
74
 * @since 2.0
Qiang Xue committed
75
 */
76
class Sort extends Object
Qiang Xue committed
77 78 79 80
{
	/**
	 * Sort ascending
	 */
Qiang Xue committed
81
	const ASC = false;
Qiang Xue committed
82 83 84 85

	/**
	 * Sort descending
	 */
Qiang Xue committed
86
	const DESC = true;
Qiang Xue committed
87 88 89 90 91

	/**
	 * @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
92
	public $enableMultiSort = false;
Qiang Xue committed
93

Qiang Xue committed
94
	/**
Qiang Xue committed
95 96
	 * @var array list of attributes that are allowed to be sorted. Its syntax can be
	 * described using the following example:
Qiang Xue committed
97
	 *
Qiang Xue committed
98
	 * ~~~
Alexander Makarov committed
99
	 * [
Qiang Xue committed
100
	 *     'age',
Alexander Makarov committed
101 102 103
	 *     'name' => [
	 *         'asc' => ['first_name' => Sort::ASC, 'last_name' => Sort::ASC],
	 *         'desc' => ['first_name' => Sort::DESC, 'last_name' => Sort::DESC],
Qiang Xue committed
104 105
	 *         'default' => Sort::DESC,
	 *         'label' => 'Name',
Alexander Makarov committed
106 107
	 *     ],
	 * ]
Qiang Xue committed
108
	 * ~~~
Qiang Xue committed
109
	 *
Qiang Xue committed
110 111
	 * In the above, two attributes are declared: "age" and "user". The "age" attribute is
	 * a simple attribute which is equivalent to the following:
Qiang Xue committed
112
	 *
Qiang Xue committed
113
	 * ~~~
Alexander Makarov committed
114 115 116
	 * 'age' => [
	 *     'asc' => ['age' => Sort::ASC],
	 *     'desc' => ['age' => Sort::DESC],
Qiang Xue committed
117 118
	 *     'default' => Sort::ASC,
	 *     'label' => Inflector::camel2words('age'),
Alexander Makarov committed
119
	 * ]
Qiang Xue committed
120
	 * ~~~
Qiang Xue committed
121
	 *
Qiang Xue committed
122 123 124 125 126 127 128
	 * The "user" attribute is a composite attribute:
	 *
	 * - The "user" key represents the attribute name which will appear in the URLs leading
	 *   to sort actions. Attribute names cannot contain characters listed in [[separators]].
	 * - 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
129 130 131 132
	 * - 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.
133
	 *   Note that it will not be HTML-encoded.
Qiang Xue committed
134 135
	 *
	 * Note that if the Sort object is already created, you can only use the full format
136
	 * to configure every attribute. Each attribute must include these elements: asc and desc.
Qiang Xue committed
137
	 */
Alexander Makarov committed
138
	public $attributes = [];
Qiang Xue committed
139
	/**
Qiang Xue committed
140
	 * @var string the name of the parameter that specifies which attributes to be sorted
Qiang Xue committed
141
	 * in which direction. Defaults to 'sort'.
Qiang Xue committed
142
	 * @see params
Qiang Xue committed
143
	 */
Qiang Xue committed
144
	public $sortVar = 'sort';
Qiang Xue committed
145
	/**
Qiang Xue committed
146
	 * @var string the tag appeared in the [[sortVar]] parameter that indicates the attribute should be sorted
Qiang Xue committed
147 148
	 * in descending order. Defaults to 'desc'.
	 */
Qiang Xue committed
149
	public $descTag = 'desc';
Qiang Xue committed
150
	/**
Qiang Xue committed
151 152
	 * @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
153
	 *
Qiang Xue committed
154
	 * ~~~
Alexander Makarov committed
155
	 * [
Qiang Xue committed
156 157
	 *     'name' => Sort::ASC,
	 *     'create_time' => Sort::DESC,
Alexander Makarov committed
158
	 * ]
Qiang Xue committed
159
	 * ~~~
Qiang Xue committed
160
	 *
Qiang Xue committed
161
	 * @see attributeOrders
Qiang Xue committed
162
	 */
Qiang Xue committed
163
	public $defaultOrder;
Qiang Xue committed
164
	/**
Qiang Xue committed
165 166
	 * @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
167
	 */
Qiang Xue committed
168
	public $route;
Qiang Xue committed
169 170 171 172
	/**
	 * @var array separators used in the generated URL. This must be an array consisting of
	 * two elements. The first element specifies the character separating different
	 * attributes, while the second element specifies the character separating attribute name
Alexander Makarov committed
173
	 * and the corresponding sort direction. Defaults to `['.', '-']`.
Qiang Xue committed
174
	 */
Alexander Makarov committed
175
	public $separators = ['.', '-'];
Qiang Xue committed
176
	/**
Qiang Xue committed
177
	 * @var array parameters (name => value) that should be used to obtain the current sort directions
Qiang Xue committed
178 179 180
	 * and to create new sort URLs. If not set, $_GET will be used instead.
	 *
	 * The array element indexed by [[sortVar]] is considered to be the current sort directions.
Qiang Xue committed
181 182 183
	 * If the element does not exist, the [[defaults|default order]] will be used.
	 *
	 * @see sortVar
Qiang Xue committed
184
	 * @see defaultOrder
Qiang Xue committed
185 186
	 */
	public $params;
Qiang Xue committed
187 188 189 190 191
	/**
	 * @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
192

Qiang Xue committed
193 194 195 196 197
	/**
	 * Normalizes the [[attributes]] property.
	 */
	public function init()
	{
Alexander Makarov committed
198
		$attributes = [];
Qiang Xue committed
199
		foreach ($this->attributes as $name => $attribute) {
Qiang Xue committed
200
			if (!is_array($attribute)) {
Alexander Makarov committed
201 202 203 204
				$attributes[$attribute] = [
					'asc' => [$attribute => self::ASC],
					'desc' => [$attribute => self::DESC],
				];
205
			} elseif (!isset($attribute['asc'], $attribute['desc'])) {
Alexander Makarov committed
206 207 208 209
				$attributes[$name] = array_merge([
					'asc' => [$name => self::ASC],
					'desc' => [$name => self::DESC],
				], $attribute);
210 211
			} else {
				$attributes[$name] = $attribute;
Qiang Xue committed
212 213 214 215 216
			}
		}
		$this->attributes = $attributes;
	}

Qiang Xue committed
217
	/**
Qiang Xue committed
218
	 * Returns the columns and their corresponding sort directions.
Qiang Xue committed
219
	 * @param boolean $recalculate whether to recalculate the sort directions
Qiang Xue committed
220 221
	 * @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
222
	 */
Qiang Xue committed
223
	public function getOrders($recalculate = false)
Qiang Xue committed
224
	{
Qiang Xue committed
225
		$attributeOrders = $this->getAttributeOrders($recalculate);
Alexander Makarov committed
226
		$orders = [];
Qiang Xue committed
227
		foreach ($attributeOrders as $attribute => $direction) {
Qiang Xue committed
228
			$definition = $this->attributes[$attribute];
Qiang Xue committed
229 230 231
			$columns = $definition[$direction === self::ASC ? 'asc' : 'desc'];
			foreach ($columns as $name => $dir) {
				$orders[$name] = $dir;
Qiang Xue committed
232 233
			}
		}
Qiang Xue committed
234
		return $orders;
Qiang Xue committed
235 236
	}

237 238 239
	/**
	 * @var array the currently requested sort order as computed by [[getAttributeOrders]].
	 */
Qiang Xue committed
240 241
	private $_attributeOrders;

Qiang Xue committed
242 243
	/**
	 * Returns the currently requested sort information.
Qiang Xue committed
244
	 * @param boolean $recalculate whether to recalculate the sort directions
Qiang Xue committed
245
	 * @return array sort directions indexed by attribute names.
Qiang Xue committed
246 247
	 * Sort direction can be either [[Sort::ASC]] for ascending order or
	 * [[Sort::DESC]] for descending order.
Qiang Xue committed
248
	 */
Qiang Xue committed
249
	public function getAttributeOrders($recalculate = false)
Qiang Xue committed
250
	{
Qiang Xue committed
251
		if ($this->_attributeOrders === null || $recalculate) {
Alexander Makarov committed
252
			$this->_attributeOrders = [];
Qiang Xue committed
253 254 255
			$params = $this->params === null ? $_GET : $this->params;
			if (isset($params[$this->sortVar]) && is_scalar($params[$this->sortVar])) {
				$attributes = explode($this->separators[0], $params[$this->sortVar]);
Qiang Xue committed
256
				foreach ($attributes as $attribute) {
Qiang Xue committed
257
					$descending = false;
Qiang Xue committed
258
					if (($pos = strrpos($attribute, $this->separators[1])) !== false) {
Qiang Xue committed
259
						if ($descending = (substr($attribute, $pos + 1) === $this->descTag)) {
Qiang Xue committed
260 261
							$attribute = substr($attribute, 0, $pos);
						}
Qiang Xue committed
262 263
					}

Qiang Xue committed
264
					if (isset($this->attributes[$attribute])) {
Qiang Xue committed
265
						$this->_attributeOrders[$attribute] = $descending;
Qiang Xue committed
266
						if (!$this->enableMultiSort) {
Qiang Xue committed
267
							return $this->_attributeOrders;
Qiang Xue committed
268
						}
Qiang Xue committed
269 270 271
					}
				}
			}
Qiang Xue committed
272 273
			if (empty($this->_attributeOrders) && is_array($this->defaultOrder)) {
				$this->_attributeOrders = $this->defaultOrder;
Qiang Xue committed
274
			}
Qiang Xue committed
275
		}
Qiang Xue committed
276
		return $this->_attributeOrders;
Qiang Xue committed
277 278 279 280 281
	}

	/**
	 * Returns the sort direction of the specified attribute in the current request.
	 * @param string $attribute the attribute name
Qiang Xue committed
282 283 284
	 * @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
	 * if the attribute is invalid or does not need to be sorted.
Qiang Xue committed
285
	 */
Qiang Xue committed
286
	public function getAttributeOrder($attribute)
Qiang Xue committed
287
	{
Qiang Xue committed
288 289
		$orders = $this->getAttributeOrders();
		return isset($orders[$attribute]) ? $orders[$attribute] : null;
Qiang Xue committed
290 291
	}

Qiang Xue committed
292 293 294 295 296
	/**
	 * 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.
297 298 299
	 * @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.
Carsten Brandt committed
300
	 * If no label is defined, [[yii\helpers\Inflector::camel2words()]] will be called to get a label.
301
	 * Note that it will not be HTML-encoded.
Qiang Xue committed
302 303 304
	 * @return string the generated hyperlink
	 * @throws InvalidConfigException if the attribute is unknown
	 */
Alexander Makarov committed
305
	public function link($attribute, $options = [])
Qiang Xue committed
306 307 308 309 310 311 312 313 314 315 316
	{
		if (($direction = $this->getAttributeOrder($attribute)) !== null) {
			$class = $direction ? 'desc' : 'asc';
			if (isset($options['class'])) {
				$options['class'] .= ' ' . $class;
			} else {
				$options['class'] = $class;
			}
		}

		$url = $this->createUrl($attribute);
Qiang Xue committed
317
		$options['data-sort'] = $this->createSortVar($attribute);
318

319 320 321 322
		if (isset($options['label'])) {
			$label = $options['label'];
			unset($options['label']);
		} else {
323 324 325 326 327
			if (isset($this->attributes[$attribute]['label'])) {
				$label = $this->attributes[$attribute]['label'];
			} else {
				$label = Inflector::camel2words($attribute);
			}
328 329
		}
		return Html::a($label, $url, $options);
Qiang Xue committed
330 331
	}

Qiang Xue committed
332
	/**
Qiang Xue committed
333
	 * Creates a URL for sorting the data by the specified attribute.
Qiang Xue committed
334
	 * This method will consider the current sorting status given by [[attributeOrders]].
Qiang Xue committed
335 336 337
	 * 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
Qiang Xue committed
338 339
	 * @return string the URL for sorting. False if the attribute is invalid.
	 * @throws InvalidConfigException if the attribute is unknown
Qiang Xue committed
340
	 * @see attributeOrders
Qiang Xue committed
341
	 * @see params
Qiang Xue committed
342
	 */
Qiang Xue committed
343
	public function createUrl($attribute)
Qiang Xue committed
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
	{
		$params = $this->params === null ? $_GET : $this->params;
		$params[$this->sortVar] = $this->createSortVar($attribute);
		$route = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
		$urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
		return $urlManager->createUrl($route, $params);
	}

	/**
	 * 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]]
	 */
	public function createSortVar($attribute)
Qiang Xue committed
361
	{
Qiang Xue committed
362
		if (!isset($this->attributes[$attribute])) {
Qiang Xue committed
363
			throw new InvalidConfigException("Unknown attribute: $attribute");
Qiang Xue committed
364
		}
Qiang Xue committed
365
		$definition = $this->attributes[$attribute];
Qiang Xue committed
366
		$directions = $this->getAttributeOrders();
Qiang Xue committed
367 368 369 370
		if (isset($directions[$attribute])) {
			$descending = !$directions[$attribute];
			unset($directions[$attribute]);
		} else {
Qiang Xue committed
371
			$descending = !empty($definition['default']);
Qiang Xue committed
372 373 374
		}

		if ($this->enableMultiSort) {
Alexander Makarov committed
375
			$directions = array_merge([$attribute => $descending], $directions);
Qiang Xue committed
376
		} else {
Alexander Makarov committed
377
			$directions = [$attribute => $descending];
Qiang Xue committed
378 379
		}

Alexander Makarov committed
380
		$sorts = [];
Qiang Xue committed
381 382 383
		foreach ($directions as $attribute => $descending) {
			$sorts[] = $descending ? $attribute . $this->separators[1] . $this->descTag : $attribute;
		}
Qiang Xue committed
384
		return implode($this->separators[0], $sorts);
Qiang Xue committed
385
	}
Qiang Xue committed
386 387 388 389 390 391 392 393 394 395

	/**
	 * 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
396
}