Model.php 20.7 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/
w  
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008-2012 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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
	/**
	 * Returns a list of scenarios and the corresponding relevant attributes.
	 * The returned array should be in the following format:
	 *
	 * ~~~
	 * array(
	 *     'scenario1' => array('attribute11', 'attribute12', ...),
	 *     'scenario2' => array('attribute21', 'attribute22', ...),
	 *     ...
	 * )
	 * ~~~
	 *
	 * Attributes relevant to the current scenario are considered safe and can be
	 * massively assigned. When [[validate()]] is invoked, these attributes will
	 * be validated using the rules declared in [[rules()]].
	 *
	 * If an attribute should NOT be massively assigned (thus considered unsafe),
	 * please prefix the attribute with an exclamation character (e.g. '!attribute').
	 *
	 * @return array a list of scenarios and the corresponding relevant attributes.
	 */
	public function scenarios()
	{
		return array();
	}

	/**
	 * 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
171 172
	/**
	 * Returns the attribute labels.
w  
Qiang Xue committed
173 174 175 176 177
	 *
	 * 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
178
	 * By default an attribute label is generated using [[generateAttributeLabel()]].
w  
Qiang Xue committed
179 180 181
	 * 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
182
	 * merge the parent labels with child labels using functions such as `array_merge()`.
w  
Qiang Xue committed
183 184 185 186 187 188 189 190 191 192
	 *
	 * @return array attribute labels (name=>label)
	 * @see generateAttributeLabel
	 */
	public function attributeLabels()
	{
		return array();
	}

	/**
w  
Qiang Xue committed
193
	 * Performs the data validation.
w  
Qiang Xue committed
194
	 *
195 196 197 198 199
	 * 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
200
	 *
Qiang Xue committed
201
	 * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
202 203
	 * after the actual validation, respectively. If [[beforeValidate()]] returns false,
	 * the validation will be cancelled and [[afterValidate()]] will not be called.
w  
Qiang Xue committed
204
	 *
205 206
	 * Errors found during the validation can be retrieved via [[getErrors()]]
	 * and [[getError()]].
w  
Qiang Xue committed
207
	 *
w  
Qiang Xue committed
208 209 210
	 * @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
211
	 * @param boolean $clearErrors whether to call [[clearErrors()]] before performing validation
w  
Qiang Xue committed
212 213
	 * @return boolean whether the validation is successful without any error.
	 */
w  
Qiang Xue committed
214
	public function validate($attributes = null, $clearErrors = true)
w  
Qiang Xue committed
215
	{
w  
Qiang Xue committed
216
		if ($clearErrors) {
w  
Qiang Xue committed
217
			$this->clearErrors();
w  
Qiang Xue committed
218
		}
219 220 221
		if ($attributes === null) {
			$attributes = $this->activeAttributes();
		}
w  
Qiang Xue committed
222
		if ($this->beforeValidate()) {
w  
Qiang Xue committed
223
			foreach ($this->getActiveValidators() as $validator) {
w  
Qiang Xue committed
224 225
				$validator->validate($this, $attributes);
			}
w  
Qiang Xue committed
226 227 228
			$this->afterValidate();
			return !$this->hasErrors();
		}
w  
Qiang Xue committed
229
		return false;
w  
Qiang Xue committed
230 231 232 233
	}

	/**
	 * This method is invoked before validation starts.
Qiang Xue committed
234
	 * The default implementation raises a `beforeValidate` event.
w  
Qiang Xue committed
235 236
	 * 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.
237
	 * @return boolean whether the validation should be executed. Defaults to true.
w  
Qiang Xue committed
238 239
	 * If false is returned, the validation will stop and the model is considered invalid.
	 */
w  
Qiang Xue committed
240
	public function beforeValidate()
w  
Qiang Xue committed
241
	{
Qiang Xue committed
242 243 244
		$event = new ModelEvent($this);
		$this->trigger('beforeValidate', $event);
		return $event->isValid;
w  
Qiang Xue committed
245 246 247 248
	}

	/**
	 * This method is invoked after validation ends.
Qiang Xue committed
249
	 * The default implementation raises an `afterValidate` event.
w  
Qiang Xue committed
250 251 252
	 * 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
253
	public function afterValidate()
w  
Qiang Xue committed
254
	{
Qiang Xue committed
255
		$this->trigger('afterValidate');
w  
Qiang Xue committed
256 257 258
	}

	/**
Qiang Xue committed
259
	 * Returns all the validators declared in [[rules()]].
w  
Qiang Xue committed
260
	 *
Qiang Xue committed
261
	 * This method differs from [[getActiveValidators()]] in that the latter
w  
Qiang Xue committed
262 263 264 265 266 267
	 * 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
268
	 * ~~~
w  
Qiang Xue committed
269 270 271 272
	 * $model->validators->add($newValidator);
	 * ~~~
	 *
	 * @return Vector all the validators declared in the model.
w  
Qiang Xue committed
273
	 */
w  
Qiang Xue committed
274
	public function getValidators()
w  
Qiang Xue committed
275
	{
w  
Qiang Xue committed
276
		if ($this->_validators === null) {
w  
Qiang Xue committed
277
			$this->_validators = $this->createValidators();
w  
Qiang Xue committed
278
		}
w  
Qiang Xue committed
279 280 281 282
		return $this->_validators;
	}

	/**
w  
Qiang Xue committed
283 284
	 * 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
285
	 * If this is null, the validators for ALL attributes in the model will be returned.
Qiang Xue committed
286
	 * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
w  
Qiang Xue committed
287
	 */
w  
Qiang Xue committed
288
	public function getActiveValidators($attribute = null)
w  
Qiang Xue committed
289
	{
w  
Qiang Xue committed
290 291
		$validators = array();
		$scenario = $this->getScenario();
292
		/** @var $validator Validator */
w  
Qiang Xue committed
293
		foreach ($this->getValidators() as $validator) {
294
			if ($validator->isActive($scenario, $attribute)) {
Qiang Xue committed
295
				$validators[] = $validator;
w  
Qiang Xue committed
296 297 298 299 300 301
			}
		}
		return $validators;
	}

	/**
Qiang Xue committed
302 303
	 * 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
304
	 * @return Vector validators
Qiang Xue committed
305
	 * @throws BadConfigException if any validation rule configuration is invalid
w  
Qiang Xue committed
306 307 308
	 */
	public function createValidators()
	{
w  
Qiang Xue committed
309 310
		$validators = new Vector;
		foreach ($this->rules() as $rule) {
311 312 313 314
			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
315
				$validators->add($validator);
Qiang Xue committed
316
			} else {
Qiang Xue committed
317
				throw new BadConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
w  
Qiang Xue committed
318
			}
w  
Qiang Xue committed
319 320 321 322 323 324 325
		}
		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
326
	 * [[\yii\validators\RequiredValidator|required]] validation rule in the
w  
Qiang Xue committed
327
	 * current [[scenario]].
w  
Qiang Xue committed
328 329 330 331 332
	 * @param string $attribute attribute name
	 * @return boolean whether the attribute is required
	 */
	public function isAttributeRequired($attribute)
	{
w  
Qiang Xue committed
333
		foreach ($this->getActiveValidators($attribute) as $validator) {
334
			if ($validator instanceof RequiredValidator) {
w  
Qiang Xue committed
335
				return true;
w  
Qiang Xue committed
336
			}
w  
Qiang Xue committed
337 338 339 340 341 342 343 344 345 346 347
		}
		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)
	{
348 349
		$scenarios = $this->scenarios();
		return in_array($attribute, $scenarios[$this->getScenario()], true);
w  
Qiang Xue committed
350 351 352 353 354 355 356 357 358 359 360
	}

	/**
	 * 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
361
		$labels = $this->attributeLabels();
Alex committed
362
		return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
w  
Qiang Xue committed
363 364 365 366
	}

	/**
	 * Returns a value indicating whether there is any validation error.
367
	 * @param string|null $attribute attribute name. Use null to check all attributes.
w  
Qiang Xue committed
368 369
	 * @return boolean whether there is any error.
	 */
w  
Qiang Xue committed
370
	public function hasErrors($attribute = null)
w  
Qiang Xue committed
371
	{
w  
Qiang Xue committed
372
		return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
w  
Qiang Xue committed
373 374 375 376 377 378
	}

	/**
	 * 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
379 380
	 * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
	 *
w  
Qiang Xue committed
381
	 * ~~~
w  
Qiang Xue committed
382
	 * array(
Qiang Xue committed
383 384 385 386 387 388 389
	 *	 'username' => array(
	 *		 'Username is required.',
	 *		 'Username must contain only word characters.',
	 *	 ),
	 *	 'email' => array(
	 *		 'Email address is invalid.',
	 *	 )
w  
Qiang Xue committed
390 391 392 393
	 * )
	 * ~~~
	 *
	 * @see getError
w  
Qiang Xue committed
394
	 */
w  
Qiang Xue committed
395
	public function getErrors($attribute = null)
w  
Qiang Xue committed
396
	{
w  
Qiang Xue committed
397
		if ($attribute === null) {
w  
Qiang Xue committed
398
			return $this->_errors === null ? array() : $this->_errors;
Qiang Xue committed
399
		} else {
w  
Qiang Xue committed
400
			return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
w  
Qiang Xue committed
401
		}
w  
Qiang Xue committed
402 403 404 405 406 407
	}

	/**
	 * 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
408
	 * @see getErrors
w  
Qiang Xue committed
409 410 411 412 413 414 415 416 417 418 419
	 */
	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
420
	public function addError($attribute, $error)
w  
Qiang Xue committed
421
	{
w  
Qiang Xue committed
422
		$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
423 424 425 426 427 428 429 430 431 432
	}

	/**
	 * 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
433 434 435
		foreach ($errors as $attribute => $error) {
			if (is_array($error)) {
				foreach ($error as $e) {
w  
Qiang Xue committed
436
					$this->_errors[$attribute][] = $e;
w  
Qiang Xue committed
437
				}
Qiang Xue committed
438
			} else {
w  
Qiang Xue committed
439
				$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
440
			}
w  
Qiang Xue committed
441 442 443 444 445 446 447
		}
	}

	/**
	 * 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
448
	public function clearErrors($attribute = null)
w  
Qiang Xue committed
449
	{
w  
Qiang Xue committed
450
		if ($attribute === null) {
w  
Qiang Xue committed
451
			$this->_errors = array();
Qiang Xue committed
452
		} else {
w  
Qiang Xue committed
453
			unset($this->_errors[$attribute]);
w  
Qiang Xue committed
454
		}
w  
Qiang Xue committed
455 456 457
	}

	/**
w  
Qiang Xue committed
458 459
	 * 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
460
	 * changing the first letter of each word to upper case.
w  
Qiang Xue committed
461
	 * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
w  
Qiang Xue committed
462 463 464 465 466
	 * @param string $name the column name
	 * @return string the attribute label
	 */
	public function generateAttributeLabel($name)
	{
Qiang Xue committed
467
		return StringHelper::camel2words($name, true);
w  
Qiang Xue committed
468 469 470
	}

	/**
w  
Qiang Xue committed
471
	 * Returns attribute values.
w  
Qiang Xue committed
472
	 * @param array $names list of attributes whose value needs to be returned.
473
	 * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
w  
Qiang Xue committed
474 475 476
	 * If it is an array, only the attributes in the array will be returned.
	 * @return array attribute values (name=>value).
	 */
w  
Qiang Xue committed
477
	public function getAttributes($names = null)
w  
Qiang Xue committed
478
	{
w  
Qiang Xue committed
479
		$values = array();
w  
Qiang Xue committed
480

w  
Qiang Xue committed
481
		if (is_array($names)) {
482
			foreach ($this->attributes() as $name) {
w  
Qiang Xue committed
483 484 485 486
				if (in_array($name, $names, true)) {
					$values[$name] = $this->$name;
				}
			}
Qiang Xue committed
487
		} else {
488
			foreach ($this->attributes() as $name) {
w  
Qiang Xue committed
489 490 491 492 493
				$values[$name] = $this->$name;
			}
		}

		return $values;
w  
Qiang Xue committed
494 495 496 497
	}

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

	/**
	 * 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
525
	public function onUnsafeAttribute($name, $value)
w  
Qiang Xue committed
526
	{
w  
Qiang Xue committed
527
		if (YII_DEBUG) {
Qiang Xue committed
528
			\Yii::warning("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.");
w  
Qiang Xue committed
529
		}
w  
Qiang Xue committed
530 531 532 533 534 535 536 537
	}

	/**
	 * Returns the scenario that this model is used in.
	 *
	 * Scenario affects how validation is performed and which attributes can
	 * be massively assigned.
	 *
538
	 * @return string the scenario that this model is in. Defaults to 'default'.
w  
Qiang Xue committed
539 540 541 542 543 544 545 546 547 548 549 550 551
	 */
	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
552
		$this->_scenario = $value;
w  
Qiang Xue committed
553 554 555
	}

	/**
556
	 * Returns the attribute names that are safe to be massively assigned in the current scenario.
w  
Qiang Xue committed
557 558
	 * @return array safe attribute names
	 */
559
	public function safeAttributes()
w  
Qiang Xue committed
560
	{
561
		$scenarios = $this->scenarios();
w  
Qiang Xue committed
562
		$attributes = array();
563 564 565
		foreach ($scenarios[$this->getScenario()] as $attribute) {
			if ($attribute[0] !== '!') {
				$attributes[] = $attribute;
w  
Qiang Xue committed
566 567
			}
		}
568 569
		return $attributes;
	}
w  
Qiang Xue committed
570

571 572 573 574 575 576 577 578 579 580 581 582
	/**
	 * Returns the attribute names that are subject to validation in the current scenario.
	 * @return array safe attribute names
	 */
	public function activeAttributes()
	{
		$scenarios = $this->scenarios();
		$attributes = $scenarios[$this->getScenario()];
		foreach ($attributes as $i => $attribute) {
			if ($attribute[0] === '!') {
				$attributes[$i] = substr($attribute, 1);
			}
w  
Qiang Xue committed
583
		}
584
		return $attributes;
w  
Qiang Xue committed
585 586 587 588 589
	}

	/**
	 * Returns an iterator for traversing the attributes in the model.
	 * This method is required by the interface IteratorAggregate.
Qiang Xue committed
590
	 * @return DictionaryIterator an iterator for traversing the items in the list.
w  
Qiang Xue committed
591 592 593
	 */
	public function getIterator()
	{
w  
Qiang Xue committed
594 595
		$attributes = $this->getAttributes();
		return new DictionaryIterator($attributes);
w  
Qiang Xue committed
596 597 598 599
	}

	/**
	 * Returns whether there is an element at the specified offset.
w  
Qiang Xue committed
600 601
	 * 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
602 603 604 605 606
	 * @param mixed $offset the offset to check on
	 * @return boolean
	 */
	public function offsetExists($offset)
	{
w  
Qiang Xue committed
607
		return property_exists($this, $offset) && $this->$offset !== null;
w  
Qiang Xue committed
608 609 610 611
	}

	/**
	 * Returns the element at the specified offset.
w  
Qiang Xue committed
612 613
	 * 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
614
	 * @param mixed $offset the offset to retrieve element.
w  
Qiang Xue committed
615 616 617 618 619 620 621 622 623
	 * @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
624 625
	 * 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
626 627 628
	 * @param integer $offset the offset to set element
	 * @param mixed $item the element value
	 */
w  
Qiang Xue committed
629
	public function offsetSet($offset, $item)
w  
Qiang Xue committed
630
	{
w  
Qiang Xue committed
631
		$this->$offset = $item;
w  
Qiang Xue committed
632 633 634 635
	}

	/**
	 * Unsets the element at the specified offset.
w  
Qiang Xue committed
636 637
	 * 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
638 639 640 641 642 643 644
	 * @param mixed $offset the offset to unset element
	 */
	public function offsetUnset($offset)
	{
		unset($this->$offset);
	}
}