CModel.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. <?php
  2. /**
  3. * CModel 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. * CModel is the base class providing the common features needed by data model objects.
  12. *
  13. * CModel defines the basic framework for data models that need to be validated.
  14. *
  15. * @property CList $validatorList All the validators declared in the model.
  16. * @property array $validators The validators applicable to the current {@link scenario}.
  17. * @property array $errors Errors for all attributes or the specified attribute. Empty array is returned if no error.
  18. * @property array $attributes Attribute values (name=>value).
  19. * @property string $scenario The scenario that this model is in.
  20. * @property array $safeAttributeNames Safe attribute names.
  21. * @property CMapIterator $iterator An iterator for traversing the items in the list.
  22. *
  23. * @author Qiang Xue <qiang.xue@gmail.com>
  24. * @package system.base
  25. * @since 1.0
  26. */
  27. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  28. {
  29. private $_errors=array(); // attribute name => array of errors
  30. private $_validators; // validators
  31. private $_scenario=''; // scenario
  32. /**
  33. * Returns the list of attribute names of the model.
  34. * @return array list of attribute names.
  35. */
  36. abstract public function attributeNames();
  37. /**
  38. * Returns the validation rules for attributes.
  39. *
  40. * This method should be overridden to declare validation rules.
  41. * Each rule is an array with the following structure:
  42. * <pre>
  43. * array('attribute list', 'validator name', 'on'=>'scenario name', ...validation parameters...)
  44. * </pre>
  45. * where
  46. * <ul>
  47. * <li>attribute list: specifies the attributes (separated by commas) to be validated;</li>
  48. * <li>validator name: specifies the validator to be used. It can be the name of a model class
  49. * method, the name of a built-in validator, or a validator class (or its path alias).
  50. * A validation method must have the following signature:
  51. * <pre>
  52. * // $params refers to validation parameters given in the rule
  53. * function validatorName($attribute,$params)
  54. * </pre>
  55. * A built-in validator refers to one of the validators declared in {@link CValidator::builtInValidators}.
  56. * And a validator class is a class extending {@link CValidator}.</li>
  57. * <li>on: this specifies the scenarios when the validation rule should be performed.
  58. * Separate different scenarios with commas. If this option is not set, the rule
  59. * will be applied in any scenario that is not listed in "except". Please see {@link scenario} for more details about this option.</li>
  60. * <li>except: this specifies the scenarios when the validation rule should not be performed.
  61. * Separate different scenarios with commas. Please see {@link scenario} for more details about this option.</li>
  62. * <li>additional parameters are used to initialize the corresponding validator properties.
  63. * Please refer to individual validator class API for possible properties.</li>
  64. * </ul>
  65. *
  66. * The following are some examples:
  67. * <pre>
  68. * array(
  69. * array('username', 'required'),
  70. * array('username', 'length', 'min'=>3, 'max'=>12),
  71. * array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
  72. * array('password', 'authenticate', 'on'=>'login'),
  73. * );
  74. * </pre>
  75. *
  76. * Note, in order to inherit rules defined in the parent class, a child class needs to
  77. * merge the parent rules with child rules using functions like array_merge().
  78. *
  79. * @return array validation rules to be applied when {@link validate()} is called.
  80. * @see scenario
  81. */
  82. public function rules()
  83. {
  84. return array();
  85. }
  86. /**
  87. * Returns a list of behaviors that this model should behave as.
  88. * The return value should be an array of behavior configurations indexed by
  89. * behavior names. Each behavior configuration can be either a string specifying
  90. * the behavior class or an array of the following structure:
  91. * <pre>
  92. * 'behaviorName'=>array(
  93. * 'class'=>'path.to.BehaviorClass',
  94. * 'property1'=>'value1',
  95. * 'property2'=>'value2',
  96. * )
  97. * </pre>
  98. *
  99. * Note, the behavior classes must implement {@link IBehavior} or extend from
  100. * {@link CBehavior}. Behaviors declared in this method will be attached
  101. * to the model when it is instantiated.
  102. *
  103. * For more details about behaviors, see {@link CComponent}.
  104. * @return array the behavior configurations (behavior name=>behavior configuration)
  105. */
  106. public function behaviors()
  107. {
  108. return array();
  109. }
  110. /**
  111. * Returns the attribute labels.
  112. * Attribute labels are mainly used in error messages of validation.
  113. * By default an attribute label is generated using {@link generateAttributeLabel}.
  114. * This method allows you to explicitly specify attribute labels.
  115. *
  116. * Note, in order to inherit labels defined in the parent class, a child class needs to
  117. * merge the parent labels with child labels using functions like array_merge().
  118. *
  119. * @return array attribute labels (name=>label)
  120. * @see generateAttributeLabel
  121. */
  122. public function attributeLabels()
  123. {
  124. return array();
  125. }
  126. /**
  127. * Performs the validation.
  128. *
  129. * This method executes the validation rules as declared in {@link rules}.
  130. * Only the rules applicable to the current {@link scenario} will be executed.
  131. * A rule is considered applicable to a scenario if its 'on' option is not set
  132. * or contains the scenario.
  133. *
  134. * Errors found during the validation can be retrieved via {@link getErrors}.
  135. *
  136. * @param array $attributes list of attributes that should be validated. Defaults to null,
  137. * meaning any attribute listed in the applicable validation rules should be
  138. * validated. If this parameter is given as a list of attributes, only
  139. * the listed attributes will be validated.
  140. * @param boolean $clearErrors whether to call {@link clearErrors} before performing validation
  141. * @return boolean whether the validation is successful without any error.
  142. * @see beforeValidate
  143. * @see afterValidate
  144. */
  145. public function validate($attributes=null, $clearErrors=true)
  146. {
  147. if($clearErrors)
  148. $this->clearErrors();
  149. if($this->beforeValidate())
  150. {
  151. foreach($this->getValidators() as $validator)
  152. $validator->validate($this,$attributes);
  153. $this->afterValidate();
  154. return !$this->hasErrors();
  155. }
  156. else
  157. return false;
  158. }
  159. /**
  160. * This method is invoked after a model instance is created by new operator.
  161. * The default implementation raises the {@link onAfterConstruct} event.
  162. * You may override this method to do postprocessing after model creation.
  163. * Make sure you call the parent implementation so that the event is raised properly.
  164. */
  165. protected function afterConstruct()
  166. {
  167. if($this->hasEventHandler('onAfterConstruct'))
  168. $this->onAfterConstruct(new CEvent($this));
  169. }
  170. /**
  171. * This method is invoked before validation starts.
  172. * The default implementation calls {@link onBeforeValidate} to raise an event.
  173. * You may override this method to do preliminary checks before validation.
  174. * Make sure the parent implementation is invoked so that the event can be raised.
  175. * @return boolean whether validation should be executed. Defaults to true.
  176. * If false is returned, the validation will stop and the model is considered invalid.
  177. */
  178. protected function beforeValidate()
  179. {
  180. $event=new CModelEvent($this);
  181. $this->onBeforeValidate($event);
  182. return $event->isValid;
  183. }
  184. /**
  185. * This method is invoked after validation ends.
  186. * The default implementation calls {@link onAfterValidate} to raise an event.
  187. * You may override this method to do postprocessing after validation.
  188. * Make sure the parent implementation is invoked so that the event can be raised.
  189. */
  190. protected function afterValidate()
  191. {
  192. $this->onAfterValidate(new CEvent($this));
  193. }
  194. /**
  195. * This event is raised after the model instance is created by new operator.
  196. * @param CEvent $event the event parameter
  197. */
  198. public function onAfterConstruct($event)
  199. {
  200. $this->raiseEvent('onAfterConstruct',$event);
  201. }
  202. /**
  203. * This event is raised before the validation is performed.
  204. * @param CModelEvent $event the event parameter
  205. */
  206. public function onBeforeValidate($event)
  207. {
  208. $this->raiseEvent('onBeforeValidate',$event);
  209. }
  210. /**
  211. * This event is raised after the validation is performed.
  212. * @param CEvent $event the event parameter
  213. */
  214. public function onAfterValidate($event)
  215. {
  216. $this->raiseEvent('onAfterValidate',$event);
  217. }
  218. /**
  219. * Returns all the validators declared in the model.
  220. * This method differs from {@link getValidators} in that the latter
  221. * would only return the validators applicable to the current {@link scenario}.
  222. * Also, since this method return a {@link CList} object, you may
  223. * manipulate it by inserting or removing validators (useful in behaviors).
  224. * For example, <code>$model->validatorList->add($newValidator)</code>.
  225. * The change made to the {@link CList} object will persist and reflect
  226. * in the result of the next call of {@link getValidators}.
  227. * @return CList all the validators declared in the model.
  228. * @since 1.1.2
  229. */
  230. public function getValidatorList()
  231. {
  232. if($this->_validators===null)
  233. $this->_validators=$this->createValidators();
  234. return $this->_validators;
  235. }
  236. /**
  237. * Returns the validators applicable to the current {@link scenario}.
  238. * @param string $attribute the name of the attribute whose validators should be returned.
  239. * If this is null, the validators for ALL attributes in the model will be returned.
  240. * @return array the validators applicable to the current {@link scenario}.
  241. */
  242. public function getValidators($attribute=null)
  243. {
  244. if($this->_validators===null)
  245. $this->_validators=$this->createValidators();
  246. $validators=array();
  247. $scenario=$this->getScenario();
  248. foreach($this->_validators as $validator)
  249. {
  250. if($validator->applyTo($scenario))
  251. {
  252. if($attribute===null || in_array($attribute,$validator->attributes,true))
  253. $validators[]=$validator;
  254. }
  255. }
  256. return $validators;
  257. }
  258. /**
  259. * Creates validator objects based on the specification in {@link rules}.
  260. * This method is mainly used internally.
  261. * @throws CException if current class has an invalid validation rule
  262. * @return CList validators built based on {@link rules()}.
  263. */
  264. public function createValidators()
  265. {
  266. $validators=new CList;
  267. foreach($this->rules() as $rule)
  268. {
  269. if(isset($rule[0],$rule[1])) // attributes, validator name
  270. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  271. else
  272. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  273. array('{class}'=>get_class($this))));
  274. }
  275. return $validators;
  276. }
  277. /**
  278. * Returns a value indicating whether the attribute is required.
  279. * This is determined by checking if the attribute is associated with a
  280. * {@link CRequiredValidator} validation rule in the current {@link scenario}.
  281. * @param string $attribute attribute name
  282. * @return boolean whether the attribute is required
  283. */
  284. public function isAttributeRequired($attribute)
  285. {
  286. foreach($this->getValidators($attribute) as $validator)
  287. {
  288. if($validator instanceof CRequiredValidator)
  289. return true;
  290. }
  291. return false;
  292. }
  293. /**
  294. * Returns a value indicating whether the attribute is safe for massive assignments.
  295. * @param string $attribute attribute name
  296. * @return boolean whether the attribute is safe for massive assignments
  297. * @since 1.1
  298. */
  299. public function isAttributeSafe($attribute)
  300. {
  301. $attributes=$this->getSafeAttributeNames();
  302. return in_array($attribute,$attributes);
  303. }
  304. /**
  305. * Returns the text label for the specified attribute.
  306. * @param string $attribute the attribute name
  307. * @return string the attribute label
  308. * @see generateAttributeLabel
  309. * @see attributeLabels
  310. */
  311. public function getAttributeLabel($attribute)
  312. {
  313. $labels=$this->attributeLabels();
  314. if(isset($labels[$attribute]))
  315. return $labels[$attribute];
  316. else
  317. return $this->generateAttributeLabel($attribute);
  318. }
  319. /**
  320. * Returns a value indicating whether there is any validation error.
  321. * @param string $attribute attribute name. Use null to check all attributes.
  322. * @return boolean whether there is any error.
  323. */
  324. public function hasErrors($attribute=null)
  325. {
  326. if($attribute===null)
  327. return $this->_errors!==array();
  328. else
  329. return isset($this->_errors[$attribute]);
  330. }
  331. /**
  332. * Returns the errors for all attribute or a single attribute.
  333. * @param string $attribute attribute name. Use null to retrieve errors for all attributes.
  334. * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
  335. */
  336. public function getErrors($attribute=null)
  337. {
  338. if($attribute===null)
  339. return $this->_errors;
  340. else
  341. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  342. }
  343. /**
  344. * Returns the first error of the specified attribute.
  345. * @param string $attribute attribute name.
  346. * @return string the error message. Null is returned if no error.
  347. */
  348. public function getError($attribute)
  349. {
  350. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  351. }
  352. /**
  353. * Adds a new error to the specified attribute.
  354. * @param string $attribute attribute name
  355. * @param string $error new error message
  356. */
  357. public function addError($attribute,$error)
  358. {
  359. $this->_errors[$attribute][]=$error;
  360. }
  361. /**
  362. * Adds a list of errors.
  363. * @param array $errors a list of errors. The array keys must be attribute names.
  364. * The array values should be error messages. If an attribute has multiple errors,
  365. * these errors must be given in terms of an array.
  366. * You may use the result of {@link getErrors} as the value for this parameter.
  367. */
  368. public function addErrors($errors)
  369. {
  370. foreach($errors as $attribute=>$error)
  371. {
  372. if(is_array($error))
  373. {
  374. foreach($error as $e)
  375. $this->addError($attribute, $e);
  376. }
  377. else
  378. $this->addError($attribute, $error);
  379. }
  380. }
  381. /**
  382. * Removes errors for all attributes or a single attribute.
  383. * @param string $attribute attribute name. Use null to remove errors for all attribute.
  384. */
  385. public function clearErrors($attribute=null)
  386. {
  387. if($attribute===null)
  388. $this->_errors=array();
  389. else
  390. unset($this->_errors[$attribute]);
  391. }
  392. /**
  393. * Generates a user friendly attribute label.
  394. * This is done by replacing underscores or dashes with blanks and
  395. * changing the first letter of each word to upper case.
  396. * For example, 'department_name' or 'DepartmentName' becomes 'Department Name'.
  397. * @param string $name the column name
  398. * @return string the attribute label
  399. */
  400. public function generateAttributeLabel($name)
  401. {
  402. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  403. }
  404. /**
  405. * Returns all attribute values.
  406. * @param array $names list of attributes whose value needs to be returned.
  407. * Defaults to null, meaning all attributes as listed in {@link attributeNames} will be returned.
  408. * If it is an array, only the attributes in the array will be returned.
  409. * @return array attribute values (name=>value).
  410. */
  411. public function getAttributes($names=null)
  412. {
  413. $values=array();
  414. foreach($this->attributeNames() as $name)
  415. $values[$name]=$this->$name;
  416. if(is_array($names))
  417. {
  418. $values2=array();
  419. foreach($names as $name)
  420. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  421. return $values2;
  422. }
  423. else
  424. return $values;
  425. }
  426. /**
  427. * Sets the attribute values in a massive way.
  428. * @param array $values attribute values (name=>value) to be set.
  429. * @param boolean $safeOnly whether the assignments should only be done to the safe attributes.
  430. * A safe attribute is one that is associated with a validation rule in the current {@link scenario}.
  431. * @see getSafeAttributeNames
  432. * @see attributeNames
  433. */
  434. public function setAttributes($values,$safeOnly=true)
  435. {
  436. if(!is_array($values))
  437. return;
  438. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  439. foreach($values as $name=>$value)
  440. {
  441. if(isset($attributes[$name]))
  442. $this->$name=$value;
  443. elseif($safeOnly)
  444. $this->onUnsafeAttribute($name,$value);
  445. }
  446. }
  447. /**
  448. * Sets the attributes to be null.
  449. * @param array $names list of attributes to be set null. If this parameter is not given,
  450. * all attributes as specified by {@link attributeNames} will have their values unset.
  451. * @since 1.1.3
  452. */
  453. public function unsetAttributes($names=null)
  454. {
  455. if($names===null)
  456. $names=$this->attributeNames();
  457. foreach($names as $name)
  458. $this->$name=null;
  459. }
  460. /**
  461. * This method is invoked when an unsafe attribute is being massively assigned.
  462. * The default implementation will log a warning message if YII_DEBUG is on.
  463. * It does nothing otherwise.
  464. * @param string $name the unsafe attribute name
  465. * @param mixed $value the attribute value
  466. * @since 1.1.1
  467. */
  468. public function onUnsafeAttribute($name,$value)
  469. {
  470. if(YII_DEBUG)
  471. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  472. }
  473. /**
  474. * Returns the scenario that this model is used in.
  475. *
  476. * Scenario affects how validation is performed and which attributes can
  477. * be massively assigned.
  478. *
  479. * A validation rule will be performed when calling {@link validate()}
  480. * if its 'except' value does not contain current scenario value while
  481. * 'on' option is not set or contains the current scenario value.
  482. *
  483. * And an attribute can be massively assigned if it is associated with
  484. * a validation rule for the current scenario. Note that an exception is
  485. * the {@link CUnsafeValidator unsafe} validator which marks the associated
  486. * attributes as unsafe and not allowed to be massively assigned.
  487. *
  488. * @return string the scenario that this model is in.
  489. */
  490. public function getScenario()
  491. {
  492. return $this->_scenario;
  493. }
  494. /**
  495. * Sets the scenario for the model.
  496. * @param string $value the scenario that this model is in.
  497. * @see getScenario
  498. */
  499. public function setScenario($value)
  500. {
  501. $this->_scenario=$value;
  502. }
  503. /**
  504. * Returns the attribute names that are safe to be massively assigned.
  505. * A safe attribute is one that is associated with a validation rule in the current {@link scenario}.
  506. * @return array safe attribute names
  507. */
  508. public function getSafeAttributeNames()
  509. {
  510. $attributes=array();
  511. $unsafe=array();
  512. foreach($this->getValidators() as $validator)
  513. {
  514. if(!$validator->safe)
  515. {
  516. foreach($validator->attributes as $name)
  517. $unsafe[]=$name;
  518. }
  519. else
  520. {
  521. foreach($validator->attributes as $name)
  522. $attributes[$name]=true;
  523. }
  524. }
  525. foreach($unsafe as $name)
  526. unset($attributes[$name]);
  527. return array_keys($attributes);
  528. }
  529. /**
  530. * Returns an iterator for traversing the attributes in the model.
  531. * This method is required by the interface IteratorAggregate.
  532. * @return CMapIterator an iterator for traversing the items in the list.
  533. */
  534. public function getIterator()
  535. {
  536. $attributes=$this->getAttributes();
  537. return new CMapIterator($attributes);
  538. }
  539. /**
  540. * Returns whether there is an element at the specified offset.
  541. * This method is required by the interface ArrayAccess.
  542. * @param mixed $offset the offset to check on
  543. * @return boolean
  544. */
  545. public function offsetExists($offset)
  546. {
  547. return property_exists($this,$offset);
  548. }
  549. /**
  550. * Returns the element at the specified offset.
  551. * This method is required by the interface ArrayAccess.
  552. * @param integer $offset the offset to retrieve element.
  553. * @return mixed the element at the offset, null if no element is found at the offset
  554. */
  555. public function offsetGet($offset)
  556. {
  557. return $this->$offset;
  558. }
  559. /**
  560. * Sets the element at the specified offset.
  561. * This method is required by the interface ArrayAccess.
  562. * @param integer $offset the offset to set element
  563. * @param mixed $item the element value
  564. */
  565. public function offsetSet($offset,$item)
  566. {
  567. $this->$offset=$item;
  568. }
  569. /**
  570. * Unsets the element at the specified offset.
  571. * This method is required by the interface ArrayAccess.
  572. * @param mixed $offset the offset to unset element
  573. */
  574. public function offsetUnset($offset)
  575. {
  576. unset($this->$offset);
  577. }
  578. }