CSort.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. <?php
  2. /**
  3. * CSort class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CSort represents information relevant to sorting.
  12. *
  13. * When data needs to be sorted according to one or several attributes,
  14. * we can use CSort to represent the sorting information and generate
  15. * appropriate hyperlinks that can lead to sort actions.
  16. *
  17. * CSort is designed to be used together with {@link CActiveRecord}.
  18. * When creating a CSort instance, you need to specify {@link modelClass}.
  19. * You can use CSort to generate hyperlinks by calling {@link link}.
  20. * You can also use CSort to modify a {@link CDbCriteria} instance by calling {@link applyOrder} so that
  21. * it can cause the query results to be sorted according to the specified
  22. * attributes.
  23. *
  24. * In order to prevent SQL injection attacks, CSort ensures that only valid model attributes
  25. * can be sorted. This is determined based on {@link modelClass} and {@link attributes}.
  26. * When {@link attributes} is not set, all attributes belonging to {@link modelClass}
  27. * can be sorted. When {@link attributes} is set, only those attributes declared in the property
  28. * can be sorted.
  29. *
  30. * By configuring {@link attributes}, one can perform more complex sorts that may
  31. * consist of things like compound attributes (e.g. sort based on the combination of
  32. * first name and last name of users).
  33. *
  34. * The property {@link attributes} should be an array of key-value pairs, where the keys
  35. * represent the attribute names, while the values represent the virtual attribute definitions.
  36. * For more details, please check the documentation about {@link attributes}.
  37. *
  38. * @property string $orderBy The order-by columns represented by this sort object.
  39. * This can be put in the ORDER BY clause of a SQL statement.
  40. * @property array $directions Sort directions indexed by attribute names.
  41. * The sort direction. Can be either CSort::SORT_ASC for ascending order or
  42. * CSort::SORT_DESC for descending order.
  43. *
  44. * @author Qiang Xue <qiang.xue@gmail.com>
  45. * @package system.web
  46. */
  47. class CSort extends CComponent
  48. {
  49. /**
  50. * Sort ascending
  51. * @since 1.1.10
  52. */
  53. const SORT_ASC = false;
  54. /**
  55. * Sort descending
  56. * @since 1.1.10
  57. */
  58. const SORT_DESC = true;
  59. /**
  60. * @var boolean whether the sorting can be applied to multiple attributes simultaneously.
  61. * Defaults to false, which means each time the data can only be sorted by one attribute.
  62. */
  63. public $multiSort=false;
  64. /**
  65. * @var string the name of the model class whose attributes can be sorted.
  66. * The model class must be a child class of {@link CActiveRecord}.
  67. */
  68. public $modelClass;
  69. /**
  70. * @var array list of attributes that are allowed to be sorted.
  71. * For example, array('user_id','create_time') would specify that only 'user_id'
  72. * and 'create_time' of the model {@link modelClass} can be sorted.
  73. * By default, this property is an empty array, which means all attributes in
  74. * {@link modelClass} are allowed to be sorted.
  75. *
  76. * This property can also be used to specify complex sorting. To do so,
  77. * a virtual attribute can be declared in terms of a key-value pair in the array.
  78. * The key refers to the name of the virtual attribute that may appear in the sort request,
  79. * while the value specifies the definition of the virtual attribute.
  80. *
  81. * In the simple case, a key-value pair can be like <code>'user'=>'user_id'</code>
  82. * where 'user' is the name of the virtual attribute while 'user_id' means the virtual
  83. * attribute is the 'user_id' attribute in the {@link modelClass}.
  84. *
  85. * A more flexible way is to specify the key-value pair as
  86. * <pre>
  87. * 'user'=>array(
  88. * 'asc'=>'first_name, last_name',
  89. * 'desc'=>'first_name DESC, last_name DESC',
  90. * 'label'=>'Name'
  91. * )
  92. * </pre>
  93. * where 'user' is the name of the virtual attribute that specifies the full name of user
  94. * (a compound attribute consisting of first name and last name of user). In this case,
  95. * we have to use an array to define the virtual attribute with three elements: 'asc',
  96. * 'desc' and 'label'.
  97. *
  98. * The above approach can also be used to declare virtual attributes that consist of relational
  99. * attributes. For example,
  100. * <pre>
  101. * 'price'=>array(
  102. * 'asc'=>'item.price',
  103. * 'desc'=>'item.price DESC',
  104. * 'label'=>'Item Price'
  105. * )
  106. * </pre>
  107. *
  108. * Note, the attribute name should not contain '-' or '.' characters because
  109. * they are used as {@link separators}.
  110. *
  111. * Starting from version 1.1.3, an additional option named 'default' can be used in the virtual attribute
  112. * declaration. This option specifies whether an attribute should be sorted in ascending or descending
  113. * order upon user clicking the corresponding sort hyperlink if it is not currently sorted. The valid
  114. * option values include 'asc' (default) and 'desc'. For example,
  115. * <pre>
  116. * 'price'=>array(
  117. * 'asc'=>'item.price',
  118. * 'desc'=>'item.price DESC',
  119. * 'label'=>'Item Price',
  120. * 'default'=>'desc',
  121. * )
  122. * </pre>
  123. *
  124. * Also starting from version 1.1.3, you can include a star ('*') element in this property so that
  125. * all model attributes are available for sorting, in addition to those virtual attributes. For example,
  126. * <pre>
  127. * 'attributes'=>array(
  128. * 'price'=>array(
  129. * 'asc'=>'item.price',
  130. * 'desc'=>'item.price DESC',
  131. * 'label'=>'Item Price',
  132. * 'default'=>'desc',
  133. * ),
  134. * '*',
  135. * )
  136. * </pre>
  137. * Note that when a name appears as both a model attribute and a virtual attribute, the position of
  138. * the star element in the array determines which one takes precedence. In particular, if the star
  139. * element is the first element in the array, the model attribute takes precedence; and if the star
  140. * element is the last one, the virtual attribute takes precedence.
  141. */
  142. public $attributes=array();
  143. /**
  144. * @var string the name of the GET parameter that specifies which attributes to be sorted
  145. * in which direction. Defaults to 'sort'.
  146. */
  147. public $sortVar='sort';
  148. /**
  149. * @var string the tag appeared in the GET parameter that indicates the attribute should be sorted
  150. * in descending order. Defaults to 'desc'.
  151. */
  152. public $descTag='desc';
  153. /**
  154. * @var mixed the default order that should be applied to the query criteria when
  155. * the current request does not specify any sort. For example, 'name, create_time DESC' or
  156. * 'UPPER(name)'.
  157. *
  158. * Starting from version 1.1.3, you can also specify the default order using an array.
  159. * The array keys could be attribute names or virtual attribute names as declared in {@link attributes},
  160. * and the array values indicate whether the sorting of the corresponding attributes should
  161. * be in descending order. For example,
  162. * <pre>
  163. * 'defaultOrder'=>array(
  164. * 'price'=>CSort::SORT_DESC,
  165. * )
  166. * </pre>
  167. * `SORT_DESC` and `SORT_ASC` are available since 1.1.10. In earlier Yii versions you should use
  168. * `true` and `false` respectively.
  169. *
  170. * Please note when using array to specify the default order, the corresponding attributes
  171. * will be put into {@link directions} and thus affect how the sort links are rendered
  172. * (e.g. an arrow may be displayed next to the currently active sort link).
  173. */
  174. public $defaultOrder;
  175. /**
  176. * @var string the route (controller ID and action ID) for generating the sorted contents.
  177. * Defaults to empty string, meaning using the currently requested route.
  178. */
  179. public $route='';
  180. /**
  181. * @var array separators used in the generated URL. This must be an array consisting of
  182. * two elements. The first element specifies the character separating different
  183. * attributes, while the second element specifies the character separating attribute name
  184. * and the corresponding sort direction. Defaults to array('-','.').
  185. */
  186. public $separators=array('-','.');
  187. /**
  188. * @var array the additional GET parameters (name=>value) that should be used when generating sort URLs.
  189. * Defaults to null, meaning using the currently available GET parameters.
  190. */
  191. public $params;
  192. private $_directions;
  193. /**
  194. * Constructor.
  195. * @param string $modelClass the class name of data models that need to be sorted.
  196. * This should be a child class of {@link CActiveRecord}.
  197. */
  198. public function __construct($modelClass=null)
  199. {
  200. $this->modelClass=$modelClass;
  201. }
  202. /**
  203. * Modifies the query criteria by changing its {@link CDbCriteria::order} property.
  204. * This method will use {@link directions} to determine which columns need to be sorted.
  205. * They will be put in the ORDER BY clause. If the criteria already has non-empty {@link CDbCriteria::order} value,
  206. * the new value will be appended to it.
  207. * @param CDbCriteria $criteria the query criteria
  208. */
  209. public function applyOrder($criteria)
  210. {
  211. $order=$this->getOrderBy($criteria);
  212. if(!empty($order))
  213. {
  214. if(!empty($criteria->order))
  215. $criteria->order.=', ';
  216. $criteria->order.=$order;
  217. }
  218. }
  219. /**
  220. * @param CDbCriteria $criteria the query criteria
  221. * @return string the order-by columns represented by this sort object.
  222. * This can be put in the ORDER BY clause of a SQL statement.
  223. * @since 1.1.0
  224. */
  225. public function getOrderBy($criteria=null)
  226. {
  227. $directions=$this->getDirections();
  228. if(empty($directions))
  229. return is_string($this->defaultOrder) ? $this->defaultOrder : '';
  230. else
  231. {
  232. if($this->modelClass!==null)
  233. $schema=$this->getModel($this->modelClass)->getDbConnection()->getSchema();
  234. $orders=array();
  235. foreach($directions as $attribute=>$descending)
  236. {
  237. $definition=$this->resolveAttribute($attribute);
  238. if(is_array($definition))
  239. {
  240. if($descending)
  241. $orders[]=isset($definition['desc']) ? (is_array($definition['desc']) ? implode(', ',$definition['desc']) : $definition['desc']) : $attribute.' DESC';
  242. else
  243. $orders[]=isset($definition['asc']) ? (is_array($definition['asc']) ? implode(', ',$definition['asc']) : $definition['asc']) : $attribute;
  244. }
  245. elseif($definition!==false)
  246. {
  247. $attribute=$definition;
  248. if(isset($schema))
  249. {
  250. if(($pos=strpos($attribute,'.'))!==false)
  251. $attribute=$schema->quoteTableName(substr($attribute,0,$pos)).'.'.$schema->quoteColumnName(substr($attribute,$pos+1));
  252. else
  253. $attribute=($criteria===null || $criteria->alias===null ? $this->getModel($this->modelClass)->getTableAlias(true) : $schema->quoteTableName($criteria->alias)).'.'.$schema->quoteColumnName($attribute);
  254. }
  255. $orders[]=$descending?$attribute.' DESC':$attribute;
  256. }
  257. }
  258. return implode(', ',$orders);
  259. }
  260. }
  261. /**
  262. * Generates a hyperlink that can be clicked to cause sorting.
  263. * @param string $attribute the attribute name. This must be the actual attribute name, not alias.
  264. * If it is an attribute of a related AR object, the name should be prefixed with
  265. * the relation name (e.g. 'author.name', where 'author' is the relation name).
  266. * @param string $label the link label. If null, the label will be determined according
  267. * to the attribute (see {@link resolveLabel}).
  268. * @param array $htmlOptions additional HTML attributes for the hyperlink tag
  269. * @return string the generated hyperlink
  270. */
  271. public function link($attribute,$label=null,$htmlOptions=array())
  272. {
  273. if($label===null)
  274. $label=$this->resolveLabel($attribute);
  275. if(($definition=$this->resolveAttribute($attribute))===false)
  276. return $label;
  277. $directions=$this->getDirections();
  278. if(isset($directions[$attribute]))
  279. {
  280. $class=$directions[$attribute] ? 'desc' : 'asc';
  281. if(isset($htmlOptions['class']))
  282. $htmlOptions['class'].=' '.$class;
  283. else
  284. $htmlOptions['class']=$class;
  285. $descending=!$directions[$attribute];
  286. unset($directions[$attribute]);
  287. }
  288. elseif(is_array($definition) && isset($definition['default']))
  289. $descending=$definition['default']==='desc';
  290. else
  291. $descending=false;
  292. if($this->multiSort)
  293. $directions=array_merge(array($attribute=>$descending),$directions);
  294. else
  295. $directions=array($attribute=>$descending);
  296. $url=$this->createUrl(Yii::app()->getController(),$directions);
  297. return $this->createLink($attribute,$label,$url,$htmlOptions);
  298. }
  299. /**
  300. * Resolves the attribute label for the specified attribute.
  301. * This will invoke {@link CActiveRecord::getAttributeLabel} to determine what label to use.
  302. * If the attribute refers to a virtual attribute declared in {@link attributes},
  303. * then the label given in the {@link attributes} will be returned instead.
  304. * @param string $attribute the attribute name.
  305. * @return string the attribute label
  306. */
  307. public function resolveLabel($attribute)
  308. {
  309. $definition=$this->resolveAttribute($attribute);
  310. if(is_array($definition))
  311. {
  312. if(isset($definition['label']))
  313. return $definition['label'];
  314. }
  315. elseif(is_string($definition))
  316. $attribute=$definition;
  317. if($this->modelClass!==null)
  318. return $this->getModel($this->modelClass)->getAttributeLabel($attribute);
  319. else
  320. return $attribute;
  321. }
  322. /**
  323. * Returns the currently requested sort information.
  324. * @return array sort directions indexed by attribute names.
  325. * Sort direction can be either CSort::SORT_ASC for ascending order or
  326. * CSort::SORT_DESC for descending order.
  327. */
  328. public function getDirections()
  329. {
  330. if($this->_directions===null)
  331. {
  332. $this->_directions=array();
  333. if(isset($_GET[$this->sortVar]) && is_string($_GET[$this->sortVar]))
  334. {
  335. $attributes=explode($this->separators[0],$_GET[$this->sortVar]);
  336. foreach($attributes as $attribute)
  337. {
  338. if(($pos=strrpos($attribute,$this->separators[1]))!==false)
  339. {
  340. $descending=substr($attribute,$pos+1)===$this->descTag;
  341. if($descending)
  342. $attribute=substr($attribute,0,$pos);
  343. }
  344. else
  345. $descending=false;
  346. if(($this->resolveAttribute($attribute))!==false)
  347. {
  348. $this->_directions[$attribute]=$descending;
  349. if(!$this->multiSort)
  350. return $this->_directions;
  351. }
  352. }
  353. }
  354. if($this->_directions===array() && is_array($this->defaultOrder))
  355. $this->_directions=$this->defaultOrder;
  356. }
  357. return $this->_directions;
  358. }
  359. /**
  360. * Returns the sort direction of the specified attribute in the current request.
  361. * @param string $attribute the attribute name
  362. * @return mixed Sort direction of the attribute. Can be either CSort::SORT_ASC
  363. * for ascending order or CSort::SORT_DESC for descending order. Value is null
  364. * if the attribute doesn't need to be sorted.
  365. */
  366. public function getDirection($attribute)
  367. {
  368. $this->getDirections();
  369. return isset($this->_directions[$attribute]) ? $this->_directions[$attribute] : null;
  370. }
  371. /**
  372. * Creates a URL that can lead to generating sorted data.
  373. * @param CController $controller the controller that will be used to create the URL.
  374. * @param array $directions the sort directions indexed by attribute names.
  375. * The sort direction can be either CSort::SORT_ASC for ascending order or
  376. * CSort::SORT_DESC for descending order.
  377. * @return string the URL for sorting
  378. */
  379. public function createUrl($controller,$directions)
  380. {
  381. $sorts=array();
  382. foreach($directions as $attribute=>$descending)
  383. $sorts[]=$descending ? $attribute.$this->separators[1].$this->descTag : $attribute;
  384. $params=$this->params===null ? $_GET : $this->params;
  385. $params[$this->sortVar]=implode($this->separators[0],$sorts);
  386. return $controller->createUrl($this->route,$params);
  387. }
  388. /**
  389. * Returns the real definition of an attribute given its name.
  390. *
  391. * The resolution is based on {@link attributes} and {@link CActiveRecord::attributeNames}.
  392. * <ul>
  393. * <li>When {@link attributes} is an empty array, if the name refers to an attribute of {@link modelClass},
  394. * then the name is returned back.</li>
  395. * <li>When {@link attributes} is not empty, if the name refers to an attribute declared in {@link attributes},
  396. * then the corresponding virtual attribute definition is returned. Starting from version 1.1.3, if {@link attributes}
  397. * contains a star ('*') element, the name will also be used to match against all model attributes.</li>
  398. * <li>In all other cases, false is returned, meaning the name does not refer to a valid attribute.</li>
  399. * </ul>
  400. * @param string $attribute the attribute name that the user requests to sort on
  401. * @return mixed the attribute name or the virtual attribute definition. False if the attribute cannot be sorted.
  402. */
  403. public function resolveAttribute($attribute)
  404. {
  405. if($this->attributes!==array())
  406. $attributes=$this->attributes;
  407. elseif($this->modelClass!==null)
  408. $attributes=$this->getModel($this->modelClass)->attributeNames();
  409. else
  410. return false;
  411. foreach($attributes as $name=>$definition)
  412. {
  413. if(is_string($name))
  414. {
  415. if($name===$attribute)
  416. return $definition;
  417. }
  418. elseif($definition==='*')
  419. {
  420. if($this->modelClass!==null && $this->getModel($this->modelClass)->hasAttribute($attribute))
  421. return $attribute;
  422. }
  423. elseif($definition===$attribute)
  424. return $attribute;
  425. }
  426. return false;
  427. }
  428. /**
  429. * Given active record class name returns new model instance.
  430. *
  431. * @param string $className active record class name.
  432. * @return CActiveRecord active record model instance.
  433. *
  434. * @since 1.1.14
  435. */
  436. protected function getModel($className)
  437. {
  438. return CActiveRecord::model($className);
  439. }
  440. /**
  441. * Creates a hyperlink based on the given label and URL.
  442. * You may override this method to customize the link generation.
  443. * @param string $attribute the name of the attribute that this link is for
  444. * @param string $label the label of the hyperlink
  445. * @param string $url the URL
  446. * @param array $htmlOptions additional HTML options
  447. * @return string the generated hyperlink
  448. */
  449. protected function createLink($attribute,$label,$url,$htmlOptions)
  450. {
  451. return CHtml::link($label,$url,$htmlOptions);
  452. }
  453. }