PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/yii/framework/web/CSort.php

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