Sort.php 13.9 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
	 *
Qiang Xue committed
101 102
	 * 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
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
	 *
Qiang Xue committed
113 114 115 116 117 118 119
	 * 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
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
	 */
Qiang Xue committed
135
	public $sortVar = 'sort';
Qiang Xue committed
136
	/**
Qiang Xue committed
137
	 * @var string the tag appeared in the [[sortVar]] parameter that indicates the attribute should be sorted
Qiang Xue committed
138 139
	 * in descending order. Defaults to 'desc'.
	 */
Qiang Xue committed
140
	public $descTag = 'desc';
Qiang Xue committed
141
	/**
Qiang Xue committed
142 143
	 * @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
144
	 *
Qiang Xue committed
145
	 * ~~~
Alexander Makarov committed
146
	 * [
147 148
	 *     'name' => SORT_ASC,
	 *     'create_time' => SORT_DESC,
Alexander Makarov committed
149
	 * ]
Qiang Xue committed
150
	 * ~~~
Qiang Xue committed
151
	 *
Qiang Xue committed
152
	 * @see attributeOrders
Qiang Xue committed
153
	 */
Qiang Xue committed
154
	public $defaultOrder;
Qiang Xue committed
155
	/**
Qiang Xue committed
156 157
	 * @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
158
	 */
Qiang Xue committed
159
	public $route;
Qiang Xue committed
160 161 162 163
	/**
	 * @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
164
	 * and the corresponding sort direction. Defaults to `['.', '-']`.
Qiang Xue committed
165
	 */
Alexander Makarov committed
166
	public $separators = ['.', '-'];
Qiang Xue committed
167
	/**
Qiang Xue committed
168
	 * @var array parameters (name => value) that should be used to obtain the current sort directions
Qiang Xue committed
169 170 171
	 * 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
172 173 174
	 * If the element does not exist, the [[defaults|default order]] will be used.
	 *
	 * @see sortVar
Qiang Xue committed
175
	 * @see defaultOrder
Qiang Xue committed
176 177
	 */
	public $params;
Qiang Xue committed
178 179 180 181 182
	/**
	 * @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
183

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

Qiang Xue committed
208
	/**
Qiang Xue committed
209
	 * Returns the columns and their corresponding sort directions.
Qiang Xue committed
210
	 * @param boolean $recalculate whether to recalculate the sort directions
Qiang Xue committed
211 212
	 * @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
213
	 */
Qiang Xue committed
214
	public function getOrders($recalculate = false)
Qiang Xue committed
215
	{
Qiang Xue committed
216
		$attributeOrders = $this->getAttributeOrders($recalculate);
Alexander Makarov committed
217
		$orders = [];
Qiang Xue committed
218
		foreach ($attributeOrders as $attribute => $direction) {
Qiang Xue committed
219
			$definition = $this->attributes[$attribute];
220
			$columns = $definition[$direction === SORT_ASC ? 'asc' : 'desc'];
Qiang Xue committed
221 222
			foreach ($columns as $name => $dir) {
				$orders[$name] = $dir;
Qiang Xue committed
223 224
			}
		}
Qiang Xue committed
225
		return $orders;
Qiang Xue committed
226 227
	}

228 229 230
	/**
	 * @var array the currently requested sort order as computed by [[getAttributeOrders]].
	 */
Qiang Xue committed
231 232
	private $_attributeOrders;

Qiang Xue committed
233 234
	/**
	 * Returns the currently requested sort information.
Qiang Xue committed
235
	 * @param boolean $recalculate whether to recalculate the sort directions
Qiang Xue committed
236
	 * @return array sort directions indexed by attribute names.
237 238
	 * Sort direction can be either `SORT_ASC` for ascending order or
	 * `SORT_DESC` for descending order.
Qiang Xue committed
239
	 */
Qiang Xue committed
240
	public function getAttributeOrders($recalculate = false)
Qiang Xue committed
241
	{
Qiang Xue committed
242
		if ($this->_attributeOrders === null || $recalculate) {
Alexander Makarov committed
243
			$this->_attributeOrders = [];
244 245 246 247
			if (($params = $this->params) === null) {
				$request = Yii::$app->getRequest();
				$params = $request instanceof Request ? $request->get() : [];
			}
Qiang Xue committed
248 249
			if (isset($params[$this->sortVar]) && is_scalar($params[$this->sortVar])) {
				$attributes = explode($this->separators[0], $params[$this->sortVar]);
Qiang Xue committed
250
				foreach ($attributes as $attribute) {
Qiang Xue committed
251
					$descending = false;
Qiang Xue committed
252
					if (($pos = strrpos($attribute, $this->separators[1])) !== false) {
Qiang Xue committed
253
						if ($descending = (substr($attribute, $pos + 1) === $this->descTag)) {
Qiang Xue committed
254 255
							$attribute = substr($attribute, 0, $pos);
						}
Qiang Xue committed
256 257
					}

Qiang Xue committed
258
					if (isset($this->attributes[$attribute])) {
259
						$this->_attributeOrders[$attribute] = $descending ? SORT_DESC : SORT_ASC;
Qiang Xue committed
260
						if (!$this->enableMultiSort) {
Qiang Xue committed
261
							return $this->_attributeOrders;
Qiang Xue committed
262
						}
Qiang Xue committed
263 264 265
					}
				}
			}
Qiang Xue committed
266 267
			if (empty($this->_attributeOrders) && is_array($this->defaultOrder)) {
				$this->_attributeOrders = $this->defaultOrder;
Qiang Xue committed
268
			}
Qiang Xue committed
269
		}
Qiang Xue committed
270
		return $this->_attributeOrders;
Qiang Xue committed
271 272 273 274 275
	}

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

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

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

313 314 315 316
		if (isset($options['label'])) {
			$label = $options['label'];
			unset($options['label']);
		} else {
317 318 319 320 321
			if (isset($this->attributes[$attribute]['label'])) {
				$label = $this->attributes[$attribute]['label'];
			} else {
				$label = Inflector::camel2words($attribute);
			}
322 323
		}
		return Html::a($label, $url, $options);
Qiang Xue committed
324 325
	}

Qiang Xue committed
326
	/**
Qiang Xue committed
327
	 * Creates a URL for sorting the data by the specified attribute.
Qiang Xue committed
328
	 * This method will consider the current sorting status given by [[attributeOrders]].
Qiang Xue committed
329 330 331
	 * 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
332
	 * @param boolean $absolute whether to create an absolute URL. Defaults to `false`.
Qiang Xue committed
333 334
	 * @return string the URL for sorting. False if the attribute is invalid.
	 * @throws InvalidConfigException if the attribute is unknown
Qiang Xue committed
335
	 * @see attributeOrders
Qiang Xue committed
336
	 * @see params
Qiang Xue committed
337
	 */
338
	public function createUrl($attribute, $absolute = false)
Qiang Xue committed
339
	{
340 341 342 343
		if (($params = $this->params) === null) {
			$request = Yii::$app->getRequest();
			$params = $request instanceof Request ? $request->get() : [];
		}
Qiang Xue committed
344 345 346
		$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;
347 348 349 350 351
		if ($absolute) {
			return $urlManager->createAbsoluteUrl($route, $params);
		} else {
			return $urlManager->createUrl($route, $params);
		}
Qiang Xue committed
352 353 354 355 356 357 358 359 360 361 362
	}

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

		if ($this->enableMultiSort) {
Qiang Xue committed
377
			$directions = array_merge([$attribute => $direction], $directions);
Qiang Xue committed
378
		} else {
Qiang Xue committed
379
			$directions = [$attribute => $direction];
Qiang Xue committed
380 381
		}

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

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