Model.php 21.3 KB
Newer Older
w  
Qiang Xue committed
1 2
<?php
/**
w  
Qiang Xue committed
3
 * Model class file.
w  
Qiang Xue committed
4 5
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
w  
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
10
namespace yii\base;
w  
Qiang Xue committed
11

Qiang Xue committed
12
use yii\util\StringHelper;
13 14
use yii\validators\Validator;
use yii\validators\RequiredValidator;
Qiang Xue committed
15

w  
Qiang Xue committed
16
/**
w  
Qiang Xue committed
17
 * Model is the base class for data models.
w  
Qiang Xue committed
18
 *
w  
Qiang Xue committed
19 20 21 22 23 24 25 26
 * Model implements the following commonly used features:
 *
 * - attribute declaration: by default, every public class member is considered as
 *   a model attribute
 * - attribute labels: each attribute may be associated with a label for display purpose
 * - massive attribute assignment
 * - scenario-based validation
 *
Qiang Xue committed
27
 * Model also raises the following events when performing data validation:
w  
Qiang Xue committed
28
 *
Qiang Xue committed
29 30
 * - [[beforeValidate]]: an event raised at the beginning of [[validate()]]
 * - [[afterValidate]]: an event raised at the end of [[validate()]]
w  
Qiang Xue committed
31 32 33
 *
 * You may directly use Model to store model data, or extend it with customization.
 * You may also customize Model by attaching [[ModelBehavior|model behaviors]].
w  
Qiang Xue committed
34
 *
Qiang Xue committed
35 36 37 38 39 40 41 42 43 44
 * @property Vector $validators All the validators declared in the model.
 * @property array $activeValidators The validators applicable to the current [[scenario]].
 * @property array $errors Errors for all attributes or the specified attribute. Empty array is returned if no error.
 * @property array $attributes Attribute values (name=>value).
 * @property string $scenario The scenario that this model is in.
 *
 * @event ModelEvent beforeValidate an event raised at the beginning of [[validate()]]. You may set
 * [[ModelEvent::isValid]] to be false to stop the validation.
 * @event Event afterValidate an event raised at the end of [[validate()]]
 *
w  
Qiang Xue committed
45
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
46
 * @since 2.0
w  
Qiang Xue committed
47
 */
Qiang Xue committed
48
class Model extends Component implements \IteratorAggregate, \ArrayAccess
w  
Qiang Xue committed
49
{
w  
Qiang Xue committed
50
	private static $_attributes = array(); // class name => array of attribute names
Qiang Xue committed
51
	private $_errors; // attribute name => array of errors
52 53
	private $_validators; // Vector of validators
	private $_scenario = 'default';
w  
Qiang Xue committed
54 55 56 57

	/**
	 * Returns the validation rules for attributes.
	 *
Qiang Xue committed
58
	 * Validation rules are used by [[validate()]] to check if attribute values are valid.
w  
Qiang Xue committed
59 60
	 * Child classes may override this method to declare different validation rules.
	 *
w  
Qiang Xue committed
61
	 * Each rule is an array with the following structure:
w  
Qiang Xue committed
62
	 *
w  
Qiang Xue committed
63
	 * ~~~
w  
Qiang Xue committed
64
	 * array(
Qiang Xue committed
65 66 67 68
	 *	 'attribute list',
	 *	 'validator type',
	 *	 'on'=>'scenario name',
	 *	 ...other parameters...
w  
Qiang Xue committed
69 70 71
	 * )
	 * ~~~
	 *
w  
Qiang Xue committed
72
	 * where
w  
Qiang Xue committed
73 74 75
	 *
	 *  - 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
76
	 *	class method, the name of a built-in validator, or a validator class name (or its path alias).
w  
Qiang Xue committed
77
	 *  - on: optional, specifies the [[scenario|scenarios]] (separated by commas) when the validation
Qiang Xue committed
78
	 *	rule can be applied. If this option is not set, the rule will apply to all scenarios.
w  
Qiang Xue committed
79
	 *  - additional name-value pairs can be specified to initialize the corresponding validator properties.
Qiang Xue committed
80
	 *	Please refer to individual validator class API for possible properties.
w  
Qiang Xue committed
81
	 *
Qiang Xue committed
82 83
	 * A validator can be either an object of a class extending [[\yii\validators\Validator]],
	 * or a model class method (called *inline validator*) that has the following signature:
w  
Qiang Xue committed
84
	 *
w  
Qiang Xue committed
85
	 * ~~~
w  
Qiang Xue committed
86
	 * // $params refers to validation parameters given in the rule
w  
Qiang Xue committed
87 88 89
	 * function validatorName($attribute, $params)
	 * ~~~
	 *
Qiang Xue committed
90 91
	 * Yii also provides a set of [[\yii\validators\Validator::builtInValidators|built-in validators]].
	 * They each has an alias name which can be used when specifying a validation rule.
w  
Qiang Xue committed
92
	 *
Qiang Xue committed
93
	 * Below are some examples:
w  
Qiang Xue committed
94
	 *
w  
Qiang Xue committed
95
	 * ~~~
w  
Qiang Xue committed
96
	 * array(
Qiang Xue committed
97
	 *   // built-in "required" validator
Qiang Xue committed
98
	 *	 array('username', 'required'),
Qiang Xue committed
99
	 *   // built-in "length" validator customized with "min" and "max" properties
Qiang Xue committed
100
	 *	 array('username', 'length', 'min'=>3, 'max'=>12),
Qiang Xue committed
101
	 *   // built-in "compare" validator that is used in "register" scenario only
Qiang Xue committed
102
	 *	 array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
Qiang Xue committed
103
	 *   // an inline validator defined via the "authenticate()" method in the model class
Qiang Xue committed
104
	 *	 array('password', 'authenticate', 'on'=>'login'),
Qiang Xue committed
105 106
	 *   // a validator of class "CaptchaValidator"
	 *   array('captcha', 'CaptchaValidator'),
w  
Qiang Xue committed
107
	 * );
w  
Qiang Xue committed
108
	 * ~~~
w  
Qiang Xue committed
109 110
	 *
	 * Note, in order to inherit rules defined in the parent class, a child class needs to
w  
Qiang Xue committed
111
	 * merge the parent rules with child rules using functions such as `array_merge()`.
w  
Qiang Xue committed
112
	 *
w  
Qiang Xue committed
113
	 * @return array validation rules
114
	 * @see scenarios
w  
Qiang Xue committed
115 116 117 118 119 120
	 */
	public function rules()
	{
		return array();
	}

121
	/**
122
	 * Returns a list of scenarios and the corresponding active attributes.
Qiang Xue committed
123
	 * An active attribute is one that is subject to validation in the current scenario.
124 125 126 127 128 129 130 131 132 133
	 * The returned array should be in the following format:
	 *
	 * ~~~
	 * array(
	 *     'scenario1' => array('attribute11', 'attribute12', ...),
	 *     'scenario2' => array('attribute21', 'attribute22', ...),
	 *     ...
	 * )
	 * ~~~
	 *
Qiang Xue committed
134
	 * By default, an active attribute that is considered safe and can be massively assigned.
135
	 * If an attribute should NOT be massively assigned (thus considered unsafe),
Qiang Xue committed
136
	 * please prefix the attribute with an exclamation character (e.g. '!rank').
137
	 *
Qiang Xue committed
138 139 140 141 142
	 * The default implementation of this method will return a 'default' scenario
	 * which corresponds to all attributes listed in the validation rules applicable
	 * to the 'default' scenario.
	 *
	 * @return array a list of scenarios and the corresponding active attributes.
143 144 145
	 */
	public function scenarios()
	{
Qiang Xue committed
146 147 148 149 150 151 152 153 154
		$attributes = array();
		foreach ($this->getActiveValidators() as $validator) {
			foreach ($validator->attributes as $name) {
				$attributes[$name] = true;
			}
		}
		return array(
			'default' => array_keys($attributes),
		);
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
	}

	/**
	 * 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 behavior.
	 * @return array list of attribute names.
	 */
	public function attributes()
	{
		$className = get_class($this);
		if (isset(self::$_attributes[$className])) {
			return self::$_attributes[$className];
		}

		$class = new \ReflectionClass($this);
		$names = array();
		foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
			$name = $property->getName();
			if (!$property->isStatic()) {
				$names[] = $name;
			}
		}
		return self::$_attributes[$className] = $names;
	}

w  
Qiang Xue committed
181 182
	/**
	 * Returns the attribute labels.
w  
Qiang Xue committed
183 184 185 186 187
	 *
	 * 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.
	 *
Qiang Xue committed
188
	 * By default an attribute label is generated using [[generateAttributeLabel()]].
w  
Qiang Xue committed
189 190 191
	 * 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
w  
Qiang Xue committed
192
	 * merge the parent labels with child labels using functions such as `array_merge()`.
w  
Qiang Xue committed
193 194 195 196 197 198 199 200 201 202
	 *
	 * @return array attribute labels (name=>label)
	 * @see generateAttributeLabel
	 */
	public function attributeLabels()
	{
		return array();
	}

	/**
w  
Qiang Xue committed
203
	 * Performs the data validation.
w  
Qiang Xue committed
204
	 *
205 206 207 208 209
	 * This method executes the validation rules applicable to the current [[scenario]].
	 * The following criteria are used to determine whether a rule is currently applicable:
	 *
	 * - the rule must be associated with the attributes relevant to the current scenario;
	 * - the rules must be effective for the current scenario.
w  
Qiang Xue committed
210
	 *
Qiang Xue committed
211
	 * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
212 213
	 * after the actual validation, respectively. If [[beforeValidate()]] returns false,
	 * the validation will be cancelled and [[afterValidate()]] will not be called.
w  
Qiang Xue committed
214
	 *
215 216
	 * Errors found during the validation can be retrieved via [[getErrors()]]
	 * and [[getError()]].
w  
Qiang Xue committed
217
	 *
w  
Qiang Xue committed
218 219 220
	 * @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.
Qiang Xue committed
221
	 * @param boolean $clearErrors whether to call [[clearErrors()]] before performing validation
w  
Qiang Xue committed
222 223
	 * @return boolean whether the validation is successful without any error.
	 */
w  
Qiang Xue committed
224
	public function validate($attributes = null, $clearErrors = true)
w  
Qiang Xue committed
225
	{
w  
Qiang Xue committed
226
		if ($clearErrors) {
w  
Qiang Xue committed
227
			$this->clearErrors();
w  
Qiang Xue committed
228
		}
229 230 231
		if ($attributes === null) {
			$attributes = $this->activeAttributes();
		}
w  
Qiang Xue committed
232
		if ($this->beforeValidate()) {
w  
Qiang Xue committed
233
			foreach ($this->getActiveValidators() as $validator) {
w  
Qiang Xue committed
234 235
				$validator->validate($this, $attributes);
			}
w  
Qiang Xue committed
236 237 238
			$this->afterValidate();
			return !$this->hasErrors();
		}
w  
Qiang Xue committed
239
		return false;
w  
Qiang Xue committed
240 241 242 243
	}

	/**
	 * This method is invoked before validation starts.
Qiang Xue committed
244
	 * The default implementation raises a `beforeValidate` event.
w  
Qiang Xue committed
245 246
	 * You may override this method to do preliminary checks before validation.
	 * Make sure the parent implementation is invoked so that the event can be raised.
247
	 * @return boolean whether the validation should be executed. Defaults to true.
w  
Qiang Xue committed
248 249
	 * If false is returned, the validation will stop and the model is considered invalid.
	 */
w  
Qiang Xue committed
250
	public function beforeValidate()
w  
Qiang Xue committed
251
	{
Qiang Xue committed
252 253 254
		$event = new ModelEvent($this);
		$this->trigger('beforeValidate', $event);
		return $event->isValid;
w  
Qiang Xue committed
255 256 257 258
	}

	/**
	 * This method is invoked after validation ends.
Qiang Xue committed
259
	 * The default implementation raises an `afterValidate` event.
w  
Qiang Xue committed
260 261 262
	 * You may override this method to do postprocessing after validation.
	 * Make sure the parent implementation is invoked so that the event can be raised.
	 */
w  
Qiang Xue committed
263
	public function afterValidate()
w  
Qiang Xue committed
264
	{
Qiang Xue committed
265
		$this->trigger('afterValidate');
w  
Qiang Xue committed
266 267 268
	}

	/**
Qiang Xue committed
269
	 * Returns all the validators declared in [[rules()]].
w  
Qiang Xue committed
270
	 *
Qiang Xue committed
271
	 * This method differs from [[getActiveValidators()]] in that the latter
w  
Qiang Xue committed
272 273 274 275 276 277
	 * only returns the validators applicable to the current [[scenario]].
	 *
	 * Because this method returns a [[Vector]] object, you may
	 * manipulate it by inserting or removing validators (useful in model behaviors).
	 * For example,
	 *
w  
Qiang Xue committed
278
	 * ~~~
w  
Qiang Xue committed
279 280 281 282
	 * $model->validators->add($newValidator);
	 * ~~~
	 *
	 * @return Vector all the validators declared in the model.
w  
Qiang Xue committed
283
	 */
w  
Qiang Xue committed
284
	public function getValidators()
w  
Qiang Xue committed
285
	{
w  
Qiang Xue committed
286
		if ($this->_validators === null) {
w  
Qiang Xue committed
287
			$this->_validators = $this->createValidators();
w  
Qiang Xue committed
288
		}
w  
Qiang Xue committed
289 290 291 292
		return $this->_validators;
	}

	/**
w  
Qiang Xue committed
293 294
	 * Returns the validators applicable to the current [[scenario]].
	 * @param string $attribute the name of the attribute whose applicable validators should be returned.
w  
Qiang Xue committed
295
	 * If this is null, the validators for ALL attributes in the model will be returned.
Qiang Xue committed
296
	 * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
w  
Qiang Xue committed
297
	 */
w  
Qiang Xue committed
298
	public function getActiveValidators($attribute = null)
w  
Qiang Xue committed
299
	{
w  
Qiang Xue committed
300 301
		$validators = array();
		$scenario = $this->getScenario();
302
		/** @var $validator Validator */
w  
Qiang Xue committed
303
		foreach ($this->getValidators() as $validator) {
Qiang Xue committed
304
			if ($validator->isActive($scenario) && ($attribute === null || in_array($attribute, $validator->attributes, true))) {
Qiang Xue committed
305
				$validators[] = $validator;
w  
Qiang Xue committed
306 307 308 309 310 311
			}
		}
		return $validators;
	}

	/**
Qiang Xue committed
312 313
	 * Creates validator objects based on the validation rules specified in [[rules()]].
	 * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
w  
Qiang Xue committed
314
	 * @return Vector validators
Qiang Xue committed
315
	 * @throws BadConfigException if any validation rule configuration is invalid
w  
Qiang Xue committed
316 317 318
	 */
	public function createValidators()
	{
w  
Qiang Xue committed
319 320
		$validators = new Vector;
		foreach ($this->rules() as $rule) {
321 322 323 324
			if ($rule instanceof Validator) {
				$validators->add($rule);
			} elseif (isset($rule[0], $rule[1])) { // attributes, validator type
				$validator = Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2));
w  
Qiang Xue committed
325
				$validators->add($validator);
Qiang Xue committed
326
			} else {
Qiang Xue committed
327
				throw new BadConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
w  
Qiang Xue committed
328
			}
w  
Qiang Xue committed
329 330 331 332 333 334 335
		}
		return $validators;
	}

	/**
	 * Returns a value indicating whether the attribute is required.
	 * This is determined by checking if the attribute is associated with a
w  
Qiang Xue committed
336
	 * [[\yii\validators\RequiredValidator|required]] validation rule in the
w  
Qiang Xue committed
337
	 * current [[scenario]].
w  
Qiang Xue committed
338 339 340 341 342
	 * @param string $attribute attribute name
	 * @return boolean whether the attribute is required
	 */
	public function isAttributeRequired($attribute)
	{
w  
Qiang Xue committed
343
		foreach ($this->getActiveValidators($attribute) as $validator) {
344
			if ($validator instanceof RequiredValidator) {
w  
Qiang Xue committed
345
				return true;
w  
Qiang Xue committed
346
			}
w  
Qiang Xue committed
347 348 349 350 351 352 353 354 355 356 357
		}
		return false;
	}

	/**
	 * 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
	 */
	public function isAttributeSafe($attribute)
	{
358
		return in_array($attribute, $this->safeAttributes(), true);
w  
Qiang Xue committed
359 360 361 362 363 364 365 366 367 368 369
	}

	/**
	 * Returns the text label for the specified attribute.
	 * @param string $attribute the attribute name
	 * @return string the attribute label
	 * @see generateAttributeLabel
	 * @see attributeLabels
	 */
	public function getAttributeLabel($attribute)
	{
w  
Qiang Xue committed
370
		$labels = $this->attributeLabels();
Alex committed
371
		return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
w  
Qiang Xue committed
372 373 374 375
	}

	/**
	 * Returns a value indicating whether there is any validation error.
376
	 * @param string|null $attribute attribute name. Use null to check all attributes.
w  
Qiang Xue committed
377 378
	 * @return boolean whether there is any error.
	 */
w  
Qiang Xue committed
379
	public function hasErrors($attribute = null)
w  
Qiang Xue committed
380
	{
w  
Qiang Xue committed
381
		return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
w  
Qiang Xue committed
382 383 384 385 386 387
	}

	/**
	 * Returns the errors for all attribute or a single attribute.
	 * @param string $attribute attribute name. Use null to retrieve errors for all attributes.
	 * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
w  
Qiang Xue committed
388 389
	 * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
	 *
w  
Qiang Xue committed
390
	 * ~~~
w  
Qiang Xue committed
391
	 * array(
Qiang Xue committed
392 393 394 395 396 397 398
	 *	 'username' => array(
	 *		 'Username is required.',
	 *		 'Username must contain only word characters.',
	 *	 ),
	 *	 'email' => array(
	 *		 'Email address is invalid.',
	 *	 )
w  
Qiang Xue committed
399 400 401 402
	 * )
	 * ~~~
	 *
	 * @see getError
w  
Qiang Xue committed
403
	 */
w  
Qiang Xue committed
404
	public function getErrors($attribute = null)
w  
Qiang Xue committed
405
	{
w  
Qiang Xue committed
406
		if ($attribute === null) {
w  
Qiang Xue committed
407
			return $this->_errors === null ? array() : $this->_errors;
Qiang Xue committed
408
		} else {
w  
Qiang Xue committed
409
			return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
w  
Qiang Xue committed
410
		}
w  
Qiang Xue committed
411 412 413 414 415 416
	}

	/**
	 * Returns the first error of the specified attribute.
	 * @param string $attribute attribute name.
	 * @return string the error message. Null is returned if no error.
w  
Qiang Xue committed
417
	 * @see getErrors
w  
Qiang Xue committed
418 419 420 421 422 423 424 425 426 427 428
	 */
	public function getError($attribute)
	{
		return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
	}

	/**
	 * Adds a new error to the specified attribute.
	 * @param string $attribute attribute name
	 * @param string $error new error message
	 */
w  
Qiang Xue committed
429
	public function addError($attribute, $error)
w  
Qiang Xue committed
430
	{
w  
Qiang Xue committed
431
		$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
432 433 434 435 436 437 438 439 440 441
	}

	/**
	 * Adds a list of errors.
	 * @param array $errors a list of errors. The array keys must be attribute names.
	 * The array values should be error messages. If an attribute has multiple errors,
	 * these errors must be given in terms of an array.
	 */
	public function addErrors($errors)
	{
w  
Qiang Xue committed
442 443 444
		foreach ($errors as $attribute => $error) {
			if (is_array($error)) {
				foreach ($error as $e) {
w  
Qiang Xue committed
445
					$this->_errors[$attribute][] = $e;
w  
Qiang Xue committed
446
				}
Qiang Xue committed
447
			} else {
w  
Qiang Xue committed
448
				$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
449
			}
w  
Qiang Xue committed
450 451 452 453 454 455 456
		}
	}

	/**
	 * Removes errors for all attributes or a single attribute.
	 * @param string $attribute attribute name. Use null to remove errors for all attribute.
	 */
w  
Qiang Xue committed
457
	public function clearErrors($attribute = null)
w  
Qiang Xue committed
458
	{
w  
Qiang Xue committed
459
		if ($attribute === null) {
w  
Qiang Xue committed
460
			$this->_errors = array();
Qiang Xue committed
461
		} else {
w  
Qiang Xue committed
462
			unset($this->_errors[$attribute]);
w  
Qiang Xue committed
463
		}
w  
Qiang Xue committed
464 465 466
	}

	/**
w  
Qiang Xue committed
467 468
	 * Generates a user friendly attribute label based on the give attribute name.
	 * This is done by replacing underscores, dashes and dots with blanks and
w  
Qiang Xue committed
469
	 * changing the first letter of each word to upper case.
w  
Qiang Xue committed
470
	 * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
w  
Qiang Xue committed
471 472 473 474 475
	 * @param string $name the column name
	 * @return string the attribute label
	 */
	public function generateAttributeLabel($name)
	{
Qiang Xue committed
476
		return StringHelper::camel2words($name, true);
w  
Qiang Xue committed
477 478 479
	}

	/**
w  
Qiang Xue committed
480
	 * Returns attribute values.
w  
Qiang Xue committed
481
	 * @param array $names list of attributes whose value needs to be returned.
482
	 * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
w  
Qiang Xue committed
483
	 * If it is an array, only the attributes in the array will be returned.
484
	 * @param array $except list of attributes whose value should NOT be returned.
w  
Qiang Xue committed
485 486
	 * @return array attribute values (name=>value).
	 */
487
	public function getAttributes($names = null, $except = array())
w  
Qiang Xue committed
488
	{
w  
Qiang Xue committed
489
		$values = array();
490 491 492 493 494 495 496 497
		if ($names === null) {
			$names = $this->attributes();
		}
		foreach ($names as $name) {
			$values[$name] = $this->$name;
		}
		foreach ($except as $name) {
			unset($values[$name]);
w  
Qiang Xue committed
498 499 500
		}

		return $values;
w  
Qiang Xue committed
501 502 503 504
	}

	/**
	 * Sets the attribute values in a massive way.
w  
Qiang Xue committed
505
	 * @param array $values attribute values (name=>value) to be assigned to the model.
w  
Qiang Xue committed
506
	 * @param boolean $safeOnly whether the assignments should only be done to the safe attributes.
w  
Qiang Xue committed
507
	 * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
508 509
	 * @see safeAttributes()
	 * @see attributes()
w  
Qiang Xue committed
510
	 */
w  
Qiang Xue committed
511
	public function setAttributes($values, $safeOnly = true)
w  
Qiang Xue committed
512
	{
w  
Qiang Xue committed
513
		if (is_array($values)) {
514
			$attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
w  
Qiang Xue committed
515 516 517
			foreach ($values as $name => $value) {
				if (isset($attributes[$name])) {
					$this->$name = $value;
Qiang Xue committed
518
				} elseif ($safeOnly) {
w  
Qiang Xue committed
519 520 521
					$this->onUnsafeAttribute($name, $value);
				}
			}
w  
Qiang Xue committed
522 523 524 525 526 527 528 529 530 531
		}
	}

	/**
	 * This method is invoked when an unsafe attribute is being massively assigned.
	 * The default implementation will log a warning message if YII_DEBUG is on.
	 * It does nothing otherwise.
	 * @param string $name the unsafe attribute name
	 * @param mixed $value the attribute value
	 */
w  
Qiang Xue committed
532
	public function onUnsafeAttribute($name, $value)
w  
Qiang Xue committed
533
	{
w  
Qiang Xue committed
534
		if (YII_DEBUG) {
Qiang Xue committed
535
			\Yii::warning("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.");
w  
Qiang Xue committed
536
		}
w  
Qiang Xue committed
537 538 539 540 541 542 543 544
	}

	/**
	 * Returns the scenario that this model is used in.
	 *
	 * Scenario affects how validation is performed and which attributes can
	 * be massively assigned.
	 *
545
	 * @return string the scenario that this model is in. Defaults to 'default'.
w  
Qiang Xue committed
546 547 548 549 550 551 552 553 554 555 556 557 558
	 */
	public function getScenario()
	{
		return $this->_scenario;
	}

	/**
	 * Sets the scenario for the model.
	 * @param string $value the scenario that this model is in.
	 * @see getScenario
	 */
	public function setScenario($value)
	{
w  
Qiang Xue committed
559
		$this->_scenario = $value;
w  
Qiang Xue committed
560 561 562
	}

	/**
563
	 * Returns the attribute names that are safe to be massively assigned in the current scenario.
w  
Qiang Xue committed
564 565
	 * @return array safe attribute names
	 */
566
	public function safeAttributes()
w  
Qiang Xue committed
567
	{
568
		$scenario = $this->getScenario();
569
		$scenarios = $this->scenarios();
Qiang Xue committed
570
		$attributes = array();
571 572 573 574 575
		if (isset($scenarios[$scenario])) {
			foreach ($scenarios[$scenario] as $attribute) {
				if ($attribute[0] !== '!') {
					$attributes[] = $attribute;
				}
w  
Qiang Xue committed
576 577
			}
		}
Qiang Xue committed
578
		return $attributes;
579
	}
w  
Qiang Xue committed
580

581 582 583 584 585 586
	/**
	 * Returns the attribute names that are subject to validation in the current scenario.
	 * @return array safe attribute names
	 */
	public function activeAttributes()
	{
587
		$scenario = $this->getScenario();
588
		$scenarios = $this->scenarios();
589 590 591 592 593 594 595
		if (isset($scenarios[$scenario])) {
			$attributes = $scenarios[$this->getScenario()];
			foreach ($attributes as $i => $attribute) {
				if ($attribute[0] === '!') {
					$attributes[$i] = substr($attribute, 1);
				}
			}
Qiang Xue committed
596
			return $attributes;
597
		} else {
Qiang Xue committed
598
			return array();
w  
Qiang Xue committed
599
		}
w  
Qiang Xue committed
600 601 602 603 604
	}

	/**
	 * Returns an iterator for traversing the attributes in the model.
	 * This method is required by the interface IteratorAggregate.
Qiang Xue committed
605
	 * @return DictionaryIterator an iterator for traversing the items in the list.
w  
Qiang Xue committed
606 607 608
	 */
	public function getIterator()
	{
w  
Qiang Xue committed
609 610
		$attributes = $this->getAttributes();
		return new DictionaryIterator($attributes);
w  
Qiang Xue committed
611 612 613 614
	}

	/**
	 * Returns whether there is an element at the specified offset.
w  
Qiang Xue committed
615 616
	 * This method is required by the SPL interface `ArrayAccess`.
	 * It is implicitly called when you use something like `isset($model[$offset])`.
w  
Qiang Xue committed
617 618 619 620 621
	 * @param mixed $offset the offset to check on
	 * @return boolean
	 */
	public function offsetExists($offset)
	{
Qiang Xue committed
622
		return $this->$offset !== null;
w  
Qiang Xue committed
623 624 625 626
	}

	/**
	 * Returns the element at the specified offset.
w  
Qiang Xue committed
627 628
	 * This method is required by the SPL interface `ArrayAccess`.
	 * It is implicitly called when you use something like `$value = $model[$offset];`.
w  
Qiang Xue committed
629
	 * @param mixed $offset the offset to retrieve element.
w  
Qiang Xue committed
630 631 632 633 634 635 636 637 638
	 * @return mixed the element at the offset, null if no element is found at the offset
	 */
	public function offsetGet($offset)
	{
		return $this->$offset;
	}

	/**
	 * Sets the element at the specified offset.
w  
Qiang Xue committed
639 640
	 * This method is required by the SPL interface `ArrayAccess`.
	 * It is implicitly called when you use something like `$model[$offset] = $item;`.
w  
Qiang Xue committed
641 642 643
	 * @param integer $offset the offset to set element
	 * @param mixed $item the element value
	 */
w  
Qiang Xue committed
644
	public function offsetSet($offset, $item)
w  
Qiang Xue committed
645
	{
w  
Qiang Xue committed
646
		$this->$offset = $item;
w  
Qiang Xue committed
647 648 649 650
	}

	/**
	 * Unsets the element at the specified offset.
w  
Qiang Xue committed
651 652
	 * This method is required by the SPL interface `ArrayAccess`.
	 * It is implicitly called when you use something like `unset($model[$offset])`.
w  
Qiang Xue committed
653 654 655 656 657 658 659
	 * @param mixed $offset the offset to unset element
	 */
	public function offsetUnset($offset)
	{
		unset($this->$offset);
	}
}