@ -1,79 +1,129 @@
<?php
/**
* C Model class file.
* Model class file.
*
* @author Qiang Xue < qiang.xue @ gmail . com >
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2011 Yii Software LLC
* @copyright Copyright © 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* C Model is the base class providing the common features needed by data model objects.
* Model is the base class providing the common features needed by data model objects.
*
* C Model defines the basic framework for data models that need to be validated.
* Model defines the basic framework for data models that need to be validated.
*
* @author Qiang Xue < qiang.xue @ gmail . com >
* @version $Id: CModel.php 3349 2011-07-08 11:27:53Z mdomba $
* @package system.base
* @since 1.0
* @since 2.0
*/
abstract class C Model extends CC omponent implements IteratorAggregate, ArrayAccess
class Model extends Component implements \IteratorAggregate, \ArrayAccess
{
private static $_attributes = array(); // class name => array of attribute names
private $_errors = array(); // attribute name => array of errors
private $_validators; // validators
private $_scenario=''; // scenario
private $_scenario; // scenario
/**
* Constructor.
* @param string $scenario name of the [[scenario]] that this model is used in.
*/
public function __construct($scenario='')
{
$this->_scenario = $scenario;
$this->init();
$this->attachBehaviors($this->behaviors());
$this->afterConstruct();
}
/**
* Initializes this model.
* This method is invoked in the constructor right after [[scenario]] is set.
* You may override this method to provide code that is needed to initialize the model (e.g. setting
* initial property values.)
*/
public function init()
{
}
/**
* Returns the list of attribute names of the model.
* Returns the list of attribute names.
* By default, this method returns all public non-static properties of the class.
* You may override this method to change the default.
* @return array list of attribute names.
* @since 1.0.1
*/
abstract public function attributeNames();
public function attributeNames()
{
$className = get_class($this);
if (isset(self::$_attributes[$className])) {
return self::$_attributes[$className];
}
$class = new ReflectionClass($this);
$names = array();
foreach ($class->getProperties() as $property) {
$name = $property->getName();
if ($property->isPublic() & & !$property->isStatic()) {
$names[] = $name;
}
}
return self::$_attributes[$className] = $names;
}
/**
* Returns the validation rules for attributes.
*
* This method should be overridden to declare validation rules.
* Validation rules are used by [[validate()]] to check if attribute values are valid.
* Child classes may override this method to declare different validation rules.
*
* Each rule is an array with the following structure:
* < pre >
* array('attribute list', 'validator name', 'on'=>'scenario name', ...validation parameters...)
* < / pre >
*
* ~~~php
* array(
* 'attribute list',
* 'validator type',
* 'on'=>'scenario name',
* ...other parameters...
* )
* ~~~
*
* where
* < ul >
* < li > attribute list: specifies the attributes (separated by commas) to be validated;< / li >
* < li > validator name: specifies the validator to be used. It can be the name of a model class
* method, the name of a built-in validator, or a validator class (or its path alias).
* A validation method must have the following signature:
* < pre >
*
* - attribute list: required, specifies the attributes (separated by commas) to be validated;
* - validator type: required, specifies the validator to be used. It can be the name of a model
* class method, the name of a built-in validator, or a validator class (or its path alias).
* - on: optional, specifies the [[scenario|scenarios]] (separated by commas) when the validation
* rule can be applied. If this option is not set, the rule will apply to any scenario.
* - additional name-value pairs can be specified to initialize the corresponding validator properties.
* Please refer to individual validator class API for possible properties.
*
* A validator can be either a model class method or an object.
* If the former, the method must have the following signature:
*
* ~~~php
* // $params refers to validation parameters given in the rule
* function validatorName($attribute, $params)
* < / pre >
* A built-in validator refers to one of the validators declared in {@link CValidator::builtInValidators}.
* And a validator class is a class extending {@link CValidator}.< / li >
* < li > on: this specifies the scenarios when the validation rule should be performed.
* Separate different scenarios with commas. If this option is not set, the rule
* will be applied in any scenario. Please see {@link scenario} for more details about this option.< / li >
* < li > additional parameters are used to initialize the corresponding validator properties.
* Please refer to individal validator class API for possible properties.< / li >
* < / ul >
* ~~~
*
* If the latter, the object must be extending from [[\yii\validators\Validator]].
* Yii provides a set of [[\yii\validators\Validator::builtInValidators|built-in validators]].
* They each have an alias name which can be used when specifying a validation rule.
*
* The following are some examples:
* < pre >
*
* ~~~php
* array(
* array('username', 'required'),
* array('username', 'length', 'min'=>3, 'max'=>12),
* array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
* array('password', 'authenticate', 'on'=>'login'),
* );
* < / pre >
* ~~~
*
* Note, in order to inherit rules defined in the parent class, a child class needs to
* merge the parent rules with child rules using functions like array_merge() .
* merge the parent rules with child rules using functions such as `array_merge()` .
*
* @return array validation rules to be applied when {@link validate()} is called.
* @see scenario
* @return array validation rules
*/
public function rules()
{
@ -85,21 +135,21 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* The return value should be an array of behavior configurations indexed by
* behavior names. Each behavior configuration can be either a string specifying
* the behavior class or an array of the following structure:
* < pre >
*
* ~~~php
* 'behaviorName' => array(
* 'class'=>'path.to. BehaviorClass',
* 'class' => 'BehaviorClass',
* 'property1' => 'value1',
* 'property2' => 'value2',
* )
* < / pre >
* ~~~
*
* Note, the behavior classes must implement {@link IBehavior} or extend from
* {@link CBehavior}. Behaviors declared in this method will be attached
* to the model when it is instantiated.
* Note, the behavior classes must extend from [[Behavior]]. Behaviors declared
* in this method will be attached to the model when it is instantiated.
*
* For more details about behaviors, see {@link CComponent} .
* @return array the behavior configurations (behavior name=>behavior configuration)
* @since 1.0.2
* For more details about behaviors, see [[Component]] .
*
* @return array the behavior configurations.
*/
public function behaviors()
{
@ -108,12 +158,16 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
/**
* Returns the attribute labels.
* Attribute labels are mainly used in error messages of validation.
* By default an attribute label is generated using {@link generateAttributeLabel}.
*
* Attribute labels are mainly used for display purpose. For example, given an attribute
* `firstName`, we can declare a label `First Name` which is more user-friendly and can
* be displayed to end users.
*
* By default an attribute label is generated using [[generateAttributeLabel]].
* This method allows you to explicitly specify attribute labels.
*
* Note, in order to inherit labels defined in the parent class, a child class needs to
* merge the parent labels with child labels using functions like array_merge().
* merge the parent labels with child labels using functions such as `array_merge()` .
*
* @return array attribute labels (name=>label)
* @see generateAttributeLabel
@ -124,36 +178,39 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
}
/**
* Performs the validation.
* Performs the data validation.
*
* This method executes the validation rules as declared in {@link rules} .
* Only the rules applicable to the current {@link scenario} will be executed.
* A rule is considered applicable to a scenario if its 'on' option is not set
* This method executes the validation rules as declared in [[rules]] .
* Only the rules applicable to the current [[scenario]] will be executed.
* A rule is considered applicable to a scenario if its `on` option is not set
* or contains the scenario.
*
* Errors found during the validation can be retrieved via {@link getErrors}.
* This method will call [[beforeValidate]] and [[afterValidate]] before and
* after actual validation, respectively. If [[beforeValidate]] returns false,
* the validation and [[afterValidate]] will be cancelled.
*
* Errors found during the validation can be retrieved via [[getErrors]].
*
* @param array $attributes list of attributes that should be validated. Defaults to null,
* meaning any attribute listed in the applicable validation rules should be
* validated. If this parameter is given as a list of attributes, only
* the listed attributes will be validated.
* @param boolean $clearErrors whether to call {@link clearErrors} before performing validation
* @param array $attributes list of attributes that should be validated.
* If this parameter is empty, it means any attribute listed in the applicable
* validation rules should be validated.
* @param boolean $clearErrors whether to call [[clearErrors]] before performing validation
* @return boolean whether the validation is successful without any error.
* @see beforeValidate
* @see afterValidate
*/
public function validate($attributes = null, $clearErrors = true)
{
if($clearErrors)
if ($clearErrors) {
$this->clearErrors();
if($this->beforeValidate())
{
foreach($this->getValidators() as $validator)
}
if ($this->beforeValidate()) {
foreach ($this->getValidators() as $validator) {
$validator->validate($this, $attributes);
}
$this->afterValidate();
return !$this->hasErrors();
}
else
return false;
}
@ -163,7 +220,7 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* You may override this method to do postprocessing after model creation.
* Make sure you call the parent implementation so that the event is raised properly.
*/
protected function afterConstruct()
public function afterConstruct()
{
if ($this->hasEventHandler('onAfterConstruct'))
$this->onAfterConstruct(new CEvent($this));
@ -177,9 +234,9 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* @return boolean whether validation should be executed. Defaults to true.
* If false is returned, the validation will stop and the model is considered invalid.
*/
protected function beforeValidate()
public function beforeValidate()
{
$event=new C ModelEvent($this);
$event = new ModelEvent($this);
$this->onBeforeValidate($event);
return $event->isValid;
}
@ -190,7 +247,7 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* You may override this method to do postprocessing after validation.
* Make sure the parent implementation is invoked so that the event can be raised.
*/
protected function afterValidate()
public function afterValidate()
{
$this->onAfterValidate(new CEvent($this));
}
@ -198,7 +255,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
/**
* This event is raised after the model instance is created by new operator.
* @param CEvent $event the event parameter
* @since 1.0.2
*/
public function onAfterConstruct($event)
{
@ -207,8 +263,7 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
/**
* This event is raised before the validation is performed.
* @param CModelEvent $event the event parameter
* @since 1.0.2
* @param ModelEvent $event the event parameter
*/
public function onBeforeValidate($event)
{
@ -218,7 +273,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
/**
* This event is raised after the validation is performed.
* @param CEvent $event the event parameter
* @since 1.0.2
*/
public function onAfterValidate($event)
{
@ -235,7 +289,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* The change made to the {@link CList} object will persist and reflect
* in the result of the next call of {@link getValidators}.
* @return CList all the validators declared in the model.
* @since 1.1.2
*/
public function getValidatorList()
{
@ -249,7 +302,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* @param string $attribute the name of the attribute whose validators should be returned.
* If this is null, the validators for ALL attributes in the model will be returned.
* @return array the validators applicable to the current {@link scenario}.
* @since 1.0.1
*/
public function getValidators($attribute = null)
{
@ -294,7 +346,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* {@link CRequiredValidator} validation rule in the current {@link scenario}.
* @param string $attribute attribute name
* @return boolean whether the attribute is required
* @since 1.0.2
*/
public function isAttributeRequired($attribute)
{
@ -310,7 +361,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* Returns a value indicating whether the attribute is safe for massive assignments.
* @param string $attribute attribute name
* @return boolean whether the attribute is safe for massive assignments
* @since 1.1
*/
public function isAttributeSafe($attribute)
{
@ -364,7 +414,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* Returns the first error of the specified attribute.
* @param string $attribute attribute name.
* @return string the error message. Null is returned if no error.
* @since 1.0.2
*/
public function getError($attribute)
{
@ -387,7 +436,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* The array values should be error messages. If an attribute has multiple errors,
* these errors must be given in terms of an array.
* You may use the result of {@link getErrors} as the value for this parameter.
* @since 1.0.5
*/
public function addErrors($errors)
{
@ -477,16 +525,17 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
/**
* Sets the attributes to be null.
* @param array $names list of attributes to be set null. If this parameter is not given,
* all attributes as specified by {@link attributeNames} will have their values unset.
* @since 1.1.3
* all attributes as specified by [[attributeNames]] will have their values unset.
*/
public function unsetAttributes($names = null)
{
if($names===null)
if ($names === null) {
$names = $this->attributeNames();
foreach($names as $name)
}
foreach ($names as $name) {
$this->$name = null;
}
}
/**
* This method is invoked when an unsafe attribute is being massively assigned.
@ -494,12 +543,11 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* It does nothing otherwise.
* @param string $name the unsafe attribute name
* @param mixed $value the attribute value
* @since 1.1.1
*/
public function onUnsafeAttribute($name, $value)
{
if (YII_DEBUG)
Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING );
\Yii::warning(sprintf('Failed to set unsafe attribute "%s" of "%s".', $name, get_class($this) );
}
/**
@ -508,16 +556,15 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* Scenario affects how validation is performed and which attributes can
* be massively assigned.
*
* A validation rule will be performed when calling {@link validate()}
* A validation rule will be performed when calling [[validate]]
* if its 'on' option is not set or contains the current scenario value.
*
* And an attribute can be massively assigned if it is associated with
* a validation rule for the current scenario. Note that a n exception is
* the {@link CUnsafeValidator unsafe} validator which marks the associated
* attributes as unsafe and not allowed to be massively assigned.
* a validation rule for the current scenario. A n exception is
* the [[\yii\validators\UnsafeValidator|unsafe]] validator which marks
* the associated attributes as unsafe and not allowed to be massively assigned.
*
* @return string the scenario that this model is in.
* @since 1.0.4
*/
public function getScenario()
{
@ -528,7 +575,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* Sets the scenario for the model.
* @param string $value the scenario that this model is in.
* @see getScenario
* @since 1.0.4
*/
public function setScenario($value)
{
@ -539,7 +585,6 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
* Returns the attribute names that are safe to be massively assigned.
* A safe attribute is one that is associated with a validation rule in the current {@link scenario}.
* @return array safe attribute names
* @since 1.0.2
*/
public function getSafeAttributeNames()
{
@ -572,27 +617,27 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
public function getIterator()
{
$attributes = $this->getAttributes();
return new CMap Iterator($attributes);
return new Dictionary Iterator($attributes);
}
/**
* Returns whether there is an element at the specified offset.
* This method is required by the interface ArrayAccess.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `isset($model[$offset])`.
* @param mixed $offset the offset to check on
* @return boolean
* @since 1.0.2
*/
public function offsetExists($offset)
{
return property_exists($this,$offset);
return property_exists($this, $offset) & & $this->$offset !== null ;
}
/**
* Returns the element at the specified offset.
* This method is required by the interface ArrayAccess.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `$value = $model[$offset];`.
* @param integer $offset the offset to retrieve element.
* @return mixed the element at the offset, null if no element is found at the offset
* @since 1.0.2
*/
public function offsetGet($offset)
{
@ -601,10 +646,10 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
/**
* Sets the element at the specified offset.
* This method is required by the interface ArrayAccess.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `$model[$offset] = $item;`.
* @param integer $offset the offset to set element
* @param mixed $item the element value
* @since 1.0.2
*/
public function offsetSet($offset, $item)
{
@ -613,9 +658,9 @@ abstract class CModel extends CComponent implements IteratorAggregate, ArrayAcce
/**
* Unsets the element at the specified offset.
* This method is required by the interface ArrayAccess.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `unset($model[$offset])`.
* @param mixed $offset the offset to unset element
* @since 1.0.2
*/
public function offsetUnset($offset)
{