Sort.php 12.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 28
 *
 * ~~~
 * function actionIndex()
 * {
 *     $sort = new Sort(array(
Qiang Xue committed
29 30 31
 *         'attributes' => array(
 *             'age',
 *             'name' => array(
Qiang Xue committed
32 33 34 35
 *                 'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC),
 *                 'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC),
 *                 'default' => Sort::DESC,
 *                 'label' => 'Name',
Qiang Xue committed
36 37
 *             ),
 *         ),
Qiang Xue committed
38
 *     ));
Qiang Xue committed
39
 *
Qiang Xue committed
40 41
 *     $models = Article::find()
 *         ->where(array('status' => 1))
Qiang Xue committed
42
 *         ->orderBy($sort->orders)
Qiang Xue committed
43 44
 *         ->all();
 *
Luciano Baraglia committed
45
 *     return $this->render('index', array(
Qiang Xue committed
46 47 48 49 50 51 52 53 54
 *          'models' => $models,
 *          'sort' => $sort,
 *     ));
 * }
 * ~~~
 *
 * View:
 *
 * ~~~
Qiang Xue committed
55 56 57
 * // display links leading to sort actions
 * echo $sort->link('name', 'Name') . ' | ' . $sort->link('age', 'Age');
 *
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.
 *
Qiang Xue committed
68
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
69
 * @since 2.0
Qiang Xue committed
70
 */
71
class Sort extends 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
	 * ~~~
	 * array(
	 *     'age',
Qiang Xue committed
96
	 *     'name' => array(
Qiang Xue committed
97 98
	 *         'asc' => array('first_name' => Sort::ASC, 'last_name' => Sort::ASC),
	 *         'desc' => array('first_name' => Sort::DESC, 'last_name' => Sort::DESC),
Qiang Xue committed
99 100
	 *         'default' => Sort::DESC,
	 *         'label' => 'Name',
Qiang Xue committed
101
	 *     ),
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 113
	 *     'default' => Sort::ASC,
	 *     'label' => Inflector::camel2words('age'),
Qiang Xue committed
114
	 * )
Qiang Xue committed
115
	 * ~~~
Qiang Xue committed
116
	 *
Qiang Xue committed
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.
Qiang Xue committed
124 125 126 127
	 * - 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.
Qiang Xue committed
128 129 130
	 *
	 * Note that if the Sort object is already created, you can only use the full format
	 * to configure every attribute. Each attribute must include these elements: asc, desc and label.
Qiang Xue committed
131
	 */
Qiang Xue committed
132
	public $attributes = array();
Qiang Xue committed
133
	/**
Qiang Xue committed
134
	 * @var string the name of the parameter that specifies which attributes to be sorted
Qiang Xue committed
135
	 * in which direction. Defaults to 'sort'.
Qiang Xue committed
136
	 * @see params
Qiang Xue committed
137
	 */
Qiang Xue committed
138
	public $sortVar = 'sort';
Qiang Xue committed
139
	/**
Qiang Xue committed
140
	 * @var string the tag appeared in the [[sortVar]] parameter that indicates the attribute should be sorted
Qiang Xue committed
141 142
	 * in descending order. Defaults to 'desc'.
	 */
Qiang Xue committed
143
	public $descTag = 'desc';
Qiang Xue committed
144
	/**
Qiang Xue committed
145 146
	 * @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
147
	 *
Qiang Xue committed
148 149 150 151
	 * ~~~
	 * array(
	 *     'name' => Sort::ASC,
	 *     'create_time' => Sort::DESC,
Qiang Xue committed
152
	 * )
Qiang Xue committed
153
	 * ~~~
Qiang Xue committed
154
	 *
Qiang Xue committed
155
	 * @see attributeOrders
Qiang Xue committed
156
	 */
Qiang Xue committed
157
	public $defaultOrder;
Qiang Xue committed
158
	/**
Qiang Xue committed
159 160
	 * @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
161
	 */
Qiang Xue committed
162
	public $route;
Qiang Xue committed
163 164 165 166
	/**
	 * @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
167
	 * and the corresponding sort direction. Defaults to `array('.', '-')`.
Qiang Xue committed
168
	 */
Qiang Xue committed
169
	public $separators = array('.', '-');
Qiang Xue committed
170
	/**
Qiang Xue committed
171
	 * @var array parameters (name => value) that should be used to obtain the current sort directions
Qiang Xue committed
172 173 174
	 * 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
175 176 177
	 * If the element does not exist, the [[defaults|default order]] will be used.
	 *
	 * @see sortVar
Qiang Xue committed
178
	 * @see defaultOrder
Qiang Xue committed
179 180
	 */
	public $params;
Qiang Xue committed
181 182 183 184 185
	/**
	 * @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
186

Qiang Xue committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
	/**
	 * Normalizes the [[attributes]] property.
	 */
	public function init()
	{
		$attributes = array();
		foreach ($this->attributes as $name => $attribute) {
			if (is_array($attribute)) {
				$attributes[$name] = $attribute;
				if (!isset($attribute['label'])) {
					$attributes[$name]['label'] = Inflector::camel2words($name);
				}
			} else {
				$attributes[$attribute] = array(
					'asc' => array($attribute => self::ASC),
					'desc' => array($attribute => self::DESC),
					'label' => Inflector::camel2words($attribute),
				);
			}
		}
		$this->attributes = $attributes;
	}

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

Qiang Xue committed
230 231
	private $_attributeOrders;

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

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

	/**
	 * Returns the sort direction of the specified attribute in the current request.
	 * @param string $attribute the attribute name
Qiang Xue committed
272 273 274
	 * @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
275
	 */
Qiang Xue committed
276
	public function getAttributeOrder($attribute)
Qiang Xue committed
277
	{
Qiang Xue committed
278 279
		$orders = $this->getAttributeOrders();
		return isset($orders[$attribute]) ? $orders[$attribute] : null;
Qiang Xue committed
280 281
	}

Qiang Xue committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	/**
	 * 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 array $options additional HTML attributes for the hyperlink tag
	 * @return string the generated hyperlink
	 * @throws InvalidConfigException if the attribute is unknown
	 */
	public function link($attribute, $options = array())
	{
		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
303 304
		$options['data-sort'] = $this->createSortVar($attribute);
		return Html::a($this->attributes[$attribute]['label'], $url, $options);
Qiang Xue committed
305 306
	}

Qiang Xue committed
307
	/**
Qiang Xue committed
308
	 * Creates a URL for sorting the data by the specified attribute.
Qiang Xue committed
309
	 * This method will consider the current sorting status given by [[attributeOrders]].
Qiang Xue committed
310 311 312
	 * 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
313 314
	 * @return string the URL for sorting. False if the attribute is invalid.
	 * @throws InvalidConfigException if the attribute is unknown
Qiang Xue committed
315
	 * @see attributeOrders
Qiang Xue committed
316
	 * @see params
Qiang Xue committed
317
	 */
Qiang Xue committed
318
	public function createUrl($attribute)
Qiang Xue committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
	{
		$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
336
	{
Qiang Xue committed
337
		if (!isset($this->attributes[$attribute])) {
Qiang Xue committed
338
			throw new InvalidConfigException("Unknown attribute: $attribute");
Qiang Xue committed
339
		}
Qiang Xue committed
340
		$definition = $this->attributes[$attribute];
Qiang Xue committed
341
		$directions = $this->getAttributeOrders();
Qiang Xue committed
342 343 344 345
		if (isset($directions[$attribute])) {
			$descending = !$directions[$attribute];
			unset($directions[$attribute]);
		} else {
Qiang Xue committed
346
			$descending = !empty($definition['default']);
Qiang Xue committed
347 348 349 350 351 352 353 354
		}

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

Qiang Xue committed
355 356 357 358
		$sorts = array();
		foreach ($directions as $attribute => $descending) {
			$sorts[] = $descending ? $attribute . $this->separators[1] . $this->descTag : $attribute;
		}
Qiang Xue committed
359
		return implode($this->separators[0], $sorts);
Qiang Xue committed
360
	}
Qiang Xue committed
361 362 363 364 365 366 367 368 369 370

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