Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

387 lines
14 KiB

13 years ago
<?php
/**
* @link http://www.yiiframework.com/
12 years ago
* @copyright Copyright (c) 2008 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\data;
12 years ago
12 years ago
use Yii;
11 years ago
use yii\base\InvalidConfigException;
use yii\base\Object;
use yii\helpers\Html;
11 years ago
use yii\helpers\Inflector;
12 years ago
13 years ago
/**
12 years ago
* Sort represents information relevant to sorting.
13 years ago
*
* When data needs to be sorted according to one or several attributes,
12 years ago
* we can use Sort to represent the sorting information and generate
13 years ago
* appropriate hyperlinks that can lead to sort actions.
*
* A typical usage example is as follows,
12 years ago
*
* ~~~
* function actionIndex()
* {
* $sort = new Sort([
* 'attributes' => [
* 'age',
* 'name' => [
* 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
* 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
* 'default' => SORT_DESC,
11 years ago
* 'label' => 'Name',
* ],
* ],
* ]);
*
12 years ago
* $models = Article::find()
* ->where(['status' => 1])
* ->orderBy($sort->orders)
12 years ago
* ->all();
*
* return $this->render('index', [
12 years ago
* 'models' => $models,
* 'sort' => $sort,
* ]);
12 years ago
* }
* ~~~
*
* View:
*
* ~~~
* // display links leading to sort actions
11 years ago
* echo $sort->link('name') . ' | ' . $sort->link('age');
*
12 years ago
* foreach ($models as $model) {
12 years ago
* // display $model here
* }
* ~~~
*
* 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 $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.
*
13 years ago
* @author Qiang Xue <qiang.xue@gmail.com>
12 years ago
* @since 2.0
13 years ago
*/
class Sort extends Object
13 years ago
{
/**
* @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.
*/
12 years ago
public $enableMultiSort = false;
12 years ago
13 years ago
/**
* @var array list of attributes that are allowed to be sorted. Its syntax can be
* described using the following example:
13 years ago
*
* ~~~
* [
* 'age',
* 'name' => [
* 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
* 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
* 'default' => SORT_DESC,
11 years ago
* 'label' => 'Name',
* ],
* ]
* ~~~
13 years ago
*
* In the above, two attributes are declared: "age" and "user". The "age" attribute is
* a simple attribute which is equivalent to the following:
13 years ago
*
* ~~~
* 'age' => [
* 'asc' => ['age' => SORT_ASC],
* 'desc' => ['age' => SORT_DESC],
* 'default' => SORT_ASC,
11 years ago
* 'label' => Inflector::camel2words('age'),
* ]
* ~~~
13 years ago
*
* 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.
11 years ago
* - 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.
* Note that it will not be HTML-encoded.
11 years ago
*
* 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 and desc.
13 years ago
*/
public $attributes = [];
13 years ago
/**
* @var string the name of the parameter that specifies which attributes to be sorted
13 years ago
* in which direction. Defaults to 'sort'.
* @see params
13 years ago
*/
12 years ago
public $sortVar = 'sort';
13 years ago
/**
* @var string the tag appeared in the [[sortVar]] parameter that indicates the attribute should be sorted
13 years ago
* in descending order. Defaults to 'desc'.
*/
12 years ago
public $descTag = 'desc';
13 years ago
/**
* @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,
13 years ago
*
* ~~~
* [
* 'name' => SORT_ASC,
* 'create_time' => SORT_DESC,
* ]
* ~~~
13 years ago
*
* @see attributeOrders
13 years ago
*/
11 years ago
public $defaultOrder;
13 years ago
/**
12 years ago
* @var string the route of the controller action for displaying the sorted contents.
* If not set, it means using the currently requested route.
13 years ago
*/
12 years ago
public $route;
13 years ago
/**
* @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
* and the corresponding sort direction. Defaults to `['.', '-']`.
13 years ago
*/
public $separators = ['.', '-'];
13 years ago
/**
* @var array parameters (name => value) that should be used to obtain the current sort directions
12 years ago
* 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.
* If the element does not exist, the [[defaults|default order]] will be used.
*
* @see sortVar
11 years ago
* @see defaultOrder
13 years ago
*/
public $params;
11 years ago
/**
* @var \yii\web\UrlManager the URL manager used for creating sort URLs. If not set,
* the "urlManager" application component will be used.
*/
public $urlManager;
13 years ago
/**
11 years ago
* Normalizes the [[attributes]] property.
*/
public function init()
{
$attributes = [];
11 years ago
foreach ($this->attributes as $name => $attribute) {
11 years ago
if (!is_array($attribute)) {
$attributes[$attribute] = [
'asc' => [$attribute => SORT_ASC],
'desc' => [$attribute => SORT_DESC],
];
} elseif (!isset($attribute['asc'], $attribute['desc'])) {
$attributes[$name] = array_merge([
'asc' => [$name => SORT_ASC],
'desc' => [$name => SORT_DESC],
], $attribute);
} else {
$attributes[$name] = $attribute;
11 years ago
}
}
$this->attributes = $attributes;
}
/**
* Returns the columns and their corresponding sort directions.
11 years ago
* @param boolean $recalculate whether to recalculate the 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.
13 years ago
*/
11 years ago
public function getOrders($recalculate = false)
13 years ago
{
11 years ago
$attributeOrders = $this->getAttributeOrders($recalculate);
$orders = [];
foreach ($attributeOrders as $attribute => $direction) {
11 years ago
$definition = $this->attributes[$attribute];
$columns = $definition[$direction === SORT_ASC ? 'asc' : 'desc'];
foreach ($columns as $name => $dir) {
$orders[$name] = $dir;
13 years ago
}
}
return $orders;
13 years ago
}
/**
* @var array the currently requested sort order as computed by [[getAttributeOrders]].
*/
private $_attributeOrders;
13 years ago
/**
* Returns the currently requested sort information.
12 years ago
* @param boolean $recalculate whether to recalculate the sort directions
13 years ago
* @return array sort directions indexed by attribute names.
* Sort direction can be either `SORT_ASC` for ascending order or
* `SORT_DESC` for descending order.
13 years ago
*/
public function getAttributeOrders($recalculate = false)
13 years ago
{
if ($this->_attributeOrders === null || $recalculate) {
$this->_attributeOrders = [];
12 years ago
$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]);
12 years ago
foreach ($attributes as $attribute) {
12 years ago
$descending = false;
12 years ago
if (($pos = strrpos($attribute, $this->separators[1])) !== false) {
12 years ago
if ($descending = (substr($attribute, $pos + 1) === $this->descTag)) {
12 years ago
$attribute = substr($attribute, 0, $pos);
}
13 years ago
}
11 years ago
if (isset($this->attributes[$attribute])) {
$this->_attributeOrders[$attribute] = $descending ? SORT_DESC : SORT_ASC;
12 years ago
if (!$this->enableMultiSort) {
return $this->_attributeOrders;
12 years ago
}
13 years ago
}
}
}
11 years ago
if (empty($this->_attributeOrders) && is_array($this->defaultOrder)) {
$this->_attributeOrders = $this->defaultOrder;
12 years ago
}
13 years ago
}
return $this->_attributeOrders;
13 years ago
}
/**
* Returns the sort direction of the specified attribute in the current request.
* @param string $attribute the attribute name
* @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.
13 years ago
*/
public function getAttributeOrder($attribute)
13 years ago
{
11 years ago
$orders = $this->getAttributeOrders();
return isset($orders[$attribute]) ? $orders[$attribute] : null;
13 years ago
}
/**
11 years ago
* 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.
* 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.
11 years ago
* If no label is defined, [[yii\helpers\Inflector::camel2words()]] will be called to get a label.
* Note that it will not be HTML-encoded.
11 years ago
* @return string the generated hyperlink
* @throws InvalidConfigException if the attribute is unknown
*/
public function link($attribute, $options = [])
11 years ago
{
if (($direction = $this->getAttributeOrder($attribute)) !== null) {
$class = $direction === SORT_DESC ? 'desc' : 'asc';
11 years ago
if (isset($options['class'])) {
$options['class'] .= ' ' . $class;
} else {
$options['class'] = $class;
}
}
$url = $this->createUrl($attribute);
11 years ago
$options['data-sort'] = $this->createSortVar($attribute);
if (isset($options['label'])) {
$label = $options['label'];
unset($options['label']);
} else {
if (isset($this->attributes[$attribute]['label'])) {
$label = $this->attributes[$attribute]['label'];
} else {
$label = Inflector::camel2words($attribute);
}
}
return Html::a($label, $url, $options);
11 years ago
}
/**
12 years ago
* Creates a URL for sorting the data by the specified attribute.
* This method will consider the current sorting status given by [[attributeOrders]].
12 years ago
* 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
11 years ago
* @return string the URL for sorting. False if the attribute is invalid.
* @throws InvalidConfigException if the attribute is unknown
* @see attributeOrders
12 years ago
* @see params
13 years ago
*/
12 years ago
public function createUrl($attribute)
13 years ago
{
11 years ago
$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)
{
11 years ago
if (!isset($this->attributes[$attribute])) {
11 years ago
throw new InvalidConfigException("Unknown attribute: $attribute");
12 years ago
}
11 years ago
$definition = $this->attributes[$attribute];
$directions = $this->getAttributeOrders();
12 years ago
if (isset($directions[$attribute])) {
11 years ago
$direction = $directions[$attribute] === SORT_DESC ? SORT_ASC : SORT_DESC;
12 years ago
unset($directions[$attribute]);
} else {
11 years ago
$direction = isset($definition['default']) ? $definition['default'] : SORT_ASC;
12 years ago
}
if ($this->enableMultiSort) {
11 years ago
$directions = array_merge([$attribute => $direction], $directions);
12 years ago
} else {
11 years ago
$directions = [$attribute => $direction];
12 years ago
}
$sorts = [];
11 years ago
foreach ($directions as $attribute => $direction) {
$sorts[] = $direction === SORT_DESC ? $attribute . $this->separators[1] . $this->descTag : $attribute;
12 years ago
}
11 years ago
return implode($this->separators[0], $sorts);
13 years ago
}
/**
* 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]);
}
}