Sort.php 11.1 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;
11
use yii\base\Object;
Qiang Xue committed
12
use yii\helpers\Html;
Qiang Xue committed
13

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

	/**
	 * Sort descending
	 */
Qiang Xue committed
82
	const DESC = true;
Qiang Xue committed
83 84 85 86 87

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

Qiang Xue committed
90
	/**
Qiang Xue committed
91 92
	 * @var array list of attributes that are allowed to be sorted. Its syntax can be
	 * described using the following example:
Qiang Xue committed
93
	 *
Qiang Xue committed
94 95 96 97 98 99 100 101
	 * ~~~
	 * array(
	 *     'age',
	 *     'user' => array(
	 *         'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC),
	 *         'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC),
	 *         'default' => 'desc',
	 *     ),
Qiang Xue committed
102
	 * )
Qiang Xue committed
103
	 * ~~~
Qiang Xue committed
104
	 *
Qiang Xue committed
105 106
	 * 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
107
	 *
Qiang Xue committed
108 109 110 111
	 * ~~~
	 * 'age' => array(
	 *     'asc' => array('age' => Sort::ASC),
	 *     'desc' => array('age' => Sort::DESC),
Qiang Xue committed
112
	 * )
Qiang Xue committed
113
	 * ~~~
Qiang Xue committed
114
	 *
Qiang Xue committed
115 116 117 118 119 120 121 122 123
	 * 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.
	 * - And the "default" element specifies if the attribute is not sorted currently,
	 *   in which direction it should be sorted (the default value is ascending order).
Qiang Xue committed
124
	 */
Qiang Xue committed
125
	public $attributes = array();
Qiang Xue committed
126
	/**
Qiang Xue committed
127
	 * @var string the name of the parameter that specifies which attributes to be sorted
Qiang Xue committed
128
	 * in which direction. Defaults to 'sort'.
Qiang Xue committed
129
	 * @see params
Qiang Xue committed
130
	 */
Qiang Xue committed
131
	public $sortVar = 'sort';
Qiang Xue committed
132
	/**
Qiang Xue committed
133
	 * @var string the tag appeared in the [[sortVar]] parameter that indicates the attribute should be sorted
Qiang Xue committed
134 135
	 * in descending order. Defaults to 'desc'.
	 */
Qiang Xue committed
136
	public $descTag = 'desc';
Qiang Xue committed
137
	/**
Qiang Xue committed
138 139
	 * @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
140
	 *
Qiang Xue committed
141 142 143 144
	 * ~~~
	 * array(
	 *     'name' => Sort::ASC,
	 *     'create_time' => Sort::DESC,
Qiang Xue committed
145
	 * )
Qiang Xue committed
146
	 * ~~~
Qiang Xue committed
147
	 *
Qiang Xue committed
148
	 * @see attributeOrders
Qiang Xue committed
149
	 */
Qiang Xue committed
150
	public $defaults;
Qiang Xue committed
151
	/**
Qiang Xue committed
152 153
	 * @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
154
	 */
Qiang Xue committed
155
	public $route;
Qiang Xue committed
156 157 158 159
	/**
	 * @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
Qiang Xue committed
160
	 * and the corresponding sort direction. Defaults to `array('-', '.')`.
Qiang Xue committed
161
	 */
Qiang Xue committed
162
	public $separators = array('-', '.');
Qiang Xue committed
163
	/**
Qiang Xue committed
164
	 * @var array parameters (name => value) that should be used to obtain the current sort directions
Qiang Xue committed
165 166 167
	 * 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
168 169 170 171
	 * If the element does not exist, the [[defaults|default order]] will be used.
	 *
	 * @see sortVar
	 * @see defaults
Qiang Xue committed
172 173 174 175
	 */
	public $params;

	/**
Qiang Xue committed
176 177 178
	 * Returns the columns and their corresponding sort directions.
	 * @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
179
	 */
Qiang Xue committed
180
	public function getOrders()
Qiang Xue committed
181
	{
Qiang Xue committed
182 183 184 185 186 187 188
		$attributeOrders = $this->getAttributeOrders();
		$orders = array();
		foreach ($attributeOrders as $attribute => $direction) {
			$definition = $this->getAttribute($attribute);
			$columns = $definition[$direction === self::ASC ? 'asc' : 'desc'];
			foreach ($columns as $name => $dir) {
				$orders[$name] = $dir;
Qiang Xue committed
189 190
			}
		}
Qiang Xue committed
191
		return $orders;
Qiang Xue committed
192 193 194
	}

	/**
Qiang Xue committed
195 196 197 198 199
	 * 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.
	 * @param string $label the link label. Note that the label will not be HTML-encoded.
Qiang Xue committed
200 201 202
	 * @param array $htmlOptions additional HTML attributes for the hyperlink tag
	 * @return string the generated hyperlink
	 */
Qiang Xue committed
203
	public function link($attribute, $label, $htmlOptions = array())
Qiang Xue committed
204
	{
Qiang Xue committed
205 206
		if (($definition = $this->getAttribute($attribute)) === false) {
			return $label;
Qiang Xue committed
207
		}
Qiang Xue committed
208

Qiang Xue committed
209
		if (($direction = $this->getAttributeOrder($attribute)) !== null) {
Qiang Xue committed
210
			$class = $direction ? 'desc' : 'asc';
Qiang Xue committed
211 212 213 214 215 216
			if (isset($htmlOptions['class'])) {
				$htmlOptions['class'] .= ' ' . $class;
			} else {
				$htmlOptions['class'] = $class;
			}
		}
Qiang Xue committed
217

Qiang Xue committed
218
		$url = $this->createUrl($attribute);
Qiang Xue committed
219

Qiang Xue committed
220
		return Html::a($label, $url, $htmlOptions);
Qiang Xue committed
221 222
	}

Qiang Xue committed
223 224
	private $_attributeOrders;

Qiang Xue committed
225 226
	/**
	 * Returns the currently requested sort information.
Qiang Xue committed
227
	 * @param boolean $recalculate whether to recalculate the sort directions
Qiang Xue committed
228
	 * @return array sort directions indexed by attribute names.
Qiang Xue committed
229 230
	 * Sort direction can be either [[Sort::ASC]] for ascending order or
	 * [[Sort::DESC]] for descending order.
Qiang Xue committed
231
	 */
Qiang Xue committed
232
	public function getAttributeOrders($recalculate = false)
Qiang Xue committed
233
	{
Qiang Xue committed
234 235
		if ($this->_attributeOrders === null || $recalculate) {
			$this->_attributeOrders = array();
Qiang Xue committed
236 237 238
			$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
239
				foreach ($attributes as $attribute) {
Qiang Xue committed
240
					$descending = false;
Qiang Xue committed
241
					if (($pos = strrpos($attribute, $this->separators[1])) !== false) {
Qiang Xue committed
242
						if ($descending = (substr($attribute, $pos + 1) === $this->descTag)) {
Qiang Xue committed
243 244
							$attribute = substr($attribute, 0, $pos);
						}
Qiang Xue committed
245 246
					}

Qiang Xue committed
247 248
					if (($this->getAttribute($attribute)) !== false) {
						$this->_attributeOrders[$attribute] = $descending;
Qiang Xue committed
249
						if (!$this->enableMultiSort) {
Qiang Xue committed
250
							return $this->_attributeOrders;
Qiang Xue committed
251
						}
Qiang Xue committed
252 253 254
					}
				}
			}
255
			if (empty($this->_attributeOrders) && is_array($this->defaults)) {
Qiang Xue committed
256
				$this->_attributeOrders = $this->defaults;
Qiang Xue committed
257
			}
Qiang Xue committed
258
		}
Qiang Xue committed
259
		return $this->_attributeOrders;
Qiang Xue committed
260 261 262 263 264
	}

	/**
	 * Returns the sort direction of the specified attribute in the current request.
	 * @param string $attribute the attribute name
Qiang Xue committed
265 266 267
	 * @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
268
	 */
Qiang Xue committed
269
	public function getAttributeOrder($attribute)
Qiang Xue committed
270
	{
Qiang Xue committed
271 272
		$this->getAttributeOrders();
		return isset($this->_attributeOrders[$attribute]) ? $this->_attributeOrders[$attribute] : null;
Qiang Xue committed
273 274 275
	}

	/**
Qiang Xue committed
276
	 * Creates a URL for sorting the data by the specified attribute.
Qiang Xue committed
277
	 * This method will consider the current sorting status given by [[attributeOrders]].
Qiang Xue committed
278 279 280 281
	 * 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
	 * @return string|boolean the URL for sorting. False if the attribute is invalid.
Qiang Xue committed
282
	 * @see attributeOrders
Qiang Xue committed
283
	 * @see params
Qiang Xue committed
284
	 */
Qiang Xue committed
285
	public function createUrl($attribute)
Qiang Xue committed
286
	{
Qiang Xue committed
287
		if (($definition = $this->getAttribute($attribute)) === false) {
Qiang Xue committed
288 289
			return false;
		}
Qiang Xue committed
290
		$directions = $this->getAttributeOrders();
Qiang Xue committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
		if (isset($directions[$attribute])) {
			$descending = !$directions[$attribute];
			unset($directions[$attribute]);
		} elseif (isset($definition['default'])) {
			$descending = $definition['default'] === 'desc';
		} else {
			$descending = false;
		}

		if ($this->enableMultiSort) {
			$directions = array_merge(array($attribute => $descending), $directions);
		} else {
			$directions = array($attribute => $descending);
		}

Qiang Xue committed
306 307 308 309 310 311
		$sorts = array();
		foreach ($directions as $attribute => $descending) {
			$sorts[] = $descending ? $attribute . $this->separators[1] . $this->descTag : $attribute;
		}
		$params = $this->params === null ? $_GET : $this->params;
		$params[$this->sortVar] = implode($this->separators[0], $sorts);
Qiang Xue committed
312
		$route = $this->route === null ? Yii::$app->controller->route : $this->route;
Qiang Xue committed
313

Qiang Xue committed
314
		return Yii::$app->getUrlManager()->createUrl($route, $params);
Qiang Xue committed
315 316 317
	}

	/**
Qiang Xue committed
318 319 320 321 322
	 * Returns the attribute definition of the specified name.
	 * @param string $name the attribute name
	 * @return array|boolean the sort definition (column names => sort directions).
	 * False is returned if the attribute cannot be sorted.
	 * @see attributes
Qiang Xue committed
323
	 */
Qiang Xue committed
324
	public function getAttribute($name)
Qiang Xue committed
325
	{
Qiang Xue committed
326 327 328
		if (isset($this->attributes[$name])) {
			return $this->attributes[$name];
		} elseif (in_array($name, $this->attributes, true)) {
Qiang Xue committed
329
			return array(
Qiang Xue committed
330 331
				'asc' => array($name => self::ASC),
				'desc' => array($name => self::DESC),
Qiang Xue committed
332
			);
Qiang Xue committed
333
		} else {
Qiang Xue committed
334
			return false;
Qiang Xue committed
335
		}
Qiang Xue committed
336
	}
Zander Baldwin committed
337
}