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

Qiang Xue committed
8 9
namespace yii\web;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\helpers\Html;
Qiang Xue committed
12

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

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

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

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

	/**
Qiang Xue committed
175 176 177
	 * 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
178
	 */
Qiang Xue committed
179
	public function getOrders()
Qiang Xue committed
180
	{
Qiang Xue committed
181 182 183 184 185 186 187
		$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
188 189
			}
		}
Qiang Xue committed
190
		return $orders;
Qiang Xue committed
191 192 193
	}

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

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

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

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

Qiang Xue committed
222 223
	private $_attributeOrders;

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

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

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

	/**
Qiang Xue committed
275
	 * Creates a URL for sorting the data by the specified attribute.
Qiang Xue committed
276
	 * This method will consider the current sorting status given by [[attributeOrders]].
Qiang Xue committed
277 278 279 280
	 * 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
281
	 * @see attributeOrders
Qiang Xue committed
282
	 * @see params
Qiang Xue committed
283
	 */
Qiang Xue committed
284
	public function createUrl($attribute)
Qiang Xue committed
285
	{
Qiang Xue committed
286
		if (($definition = $this->getAttribute($attribute)) === false) {
Qiang Xue committed
287 288
			return false;
		}
Qiang Xue committed
289
		$directions = $this->getAttributeOrders();
Qiang Xue committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
		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
305 306 307 308 309 310
		$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
311
		$route = $this->route === null ? Yii::$app->controller->route : $this->route;
Qiang Xue committed
312

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

	/**
Qiang Xue committed
317 318 319 320 321
	 * 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
322
	 */
Qiang Xue committed
323
	public function getAttribute($name)
Qiang Xue committed
324
	{
Qiang Xue committed
325 326 327
		if (isset($this->attributes[$name])) {
			return $this->attributes[$name];
		} elseif (in_array($name, $this->attributes, true)) {
Qiang Xue committed
328
			return array(
Qiang Xue committed
329 330
				'asc' => array($name => self::ASC),
				'desc' => array($name => self::DESC),
Qiang Xue committed
331
			);
Qiang Xue committed
332
		} else {
Qiang Xue committed
333
			return false;
Qiang Xue committed
334
		}
Qiang Xue committed
335
	}
Zander Baldwin committed
336
}