Model.php 20 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 13
use yii\util\Text;

w  
Qiang Xue committed
14
/**
w  
Qiang Xue committed
15
 * Model is the base class for data models.
w  
Qiang Xue committed
16
 *
w  
Qiang Xue committed
17 18 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
 *
 * Model also provides a set of events for further customization:
 *
Qiang Xue committed
27 28
 * - [[onBeforeValidate]]: an event raised at the beginning of [[validate()]]
 * - [[onAfterValidate]]: an event raised at the end of [[validate()]]
w  
Qiang Xue committed
29 30 31
 *
 * 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
32 33
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
34
 * @since 2.0
w  
Qiang Xue committed
35
 */
Qiang Xue committed
36
class Model extends Component implements \IteratorAggregate, \ArrayAccess
w  
Qiang Xue committed
37
{
w  
Qiang Xue committed
38
	private static $_attributes = array(); // class name => array of attribute names
Qiang Xue committed
39 40 41
	private $_errors; // attribute name => array of errors
	private $_validators; // validators
	private $_scenario; // scenario
w  
Qiang Xue committed
42 43 44 45 46

	/**
	 * Constructor.
	 * @param string $scenario name of the [[scenario]] that this model is used in.
	 */
Qiang Xue committed
47
	public function __construct($scenario = '')
w  
Qiang Xue committed
48 49 50 51
	{
		$this->_scenario = $scenario;
	}

w  
Qiang Xue committed
52
	/**
w  
Qiang Xue committed
53 54
	 * Returns the list of attribute names.
	 * By default, this method returns all public non-static properties of the class.
Qiang Xue committed
55
	 * You may override this method to change the default behavior.
w  
Qiang Xue committed
56 57
	 * @return array list of attribute names.
	 */
w  
Qiang Xue committed
58 59 60 61 62 63 64
	public function attributeNames()
	{
		$className = get_class($this);
		if (isset(self::$_attributes[$className])) {
			return self::$_attributes[$className];
		}

w  
Qiang Xue committed
65
		$class = new \ReflectionClass($this);
w  
Qiang Xue committed
66
		$names = array();
w  
Qiang Xue committed
67
		foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
w  
Qiang Xue committed
68
			$name = $property->getName();
w  
Qiang Xue committed
69
			if (!$property->isStatic()) {
w  
Qiang Xue committed
70 71 72 73 74
				$names[] = $name;
			}
		}
		return self::$_attributes[$className] = $names;
	}
w  
Qiang Xue committed
75 76 77 78

	/**
	 * Returns the validation rules for attributes.
	 *
Qiang Xue committed
79
	 * Validation rules are used by [[validate()]] to check if attribute values are valid.
w  
Qiang Xue committed
80 81
	 * Child classes may override this method to declare different validation rules.
	 *
w  
Qiang Xue committed
82
	 * Each rule is an array with the following structure:
w  
Qiang Xue committed
83
	 *
w  
Qiang Xue committed
84
	 * ~~~
w  
Qiang Xue committed
85
	 * array(
Qiang Xue committed
86 87 88 89
	 *	 'attribute list',
	 *	 'validator type',
	 *	 'on'=>'scenario name',
	 *	 ...other parameters...
w  
Qiang Xue committed
90 91 92
	 * )
	 * ~~~
	 *
w  
Qiang Xue committed
93
	 * where
w  
Qiang Xue committed
94 95 96
	 *
	 *  - 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
Qiang Xue committed
97
	 *	class method, the name of a built-in validator, or a validator class (or its path alias).
w  
Qiang Xue committed
98
	 *  - on: optional, specifies the [[scenario|scenarios]] (separated by commas) when the validation
Qiang Xue committed
99
	 *	rule can be applied. If this option is not set, the rule will apply to all scenarios.
w  
Qiang Xue committed
100
	 *  - additional name-value pairs can be specified to initialize the corresponding validator properties.
Qiang Xue committed
101
	 *	Please refer to individual validator class API for possible properties.
w  
Qiang Xue committed
102
	 *
Qiang Xue committed
103 104
	 * 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
105
	 *
w  
Qiang Xue committed
106
	 * ~~~
w  
Qiang Xue committed
107
	 * // $params refers to validation parameters given in the rule
w  
Qiang Xue committed
108 109 110
	 * function validatorName($attribute, $params)
	 * ~~~
	 *
Qiang Xue committed
111 112
	 * 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
113
	 *
Qiang Xue committed
114
	 * Below are some examples:
w  
Qiang Xue committed
115
	 *
w  
Qiang Xue committed
116
	 * ~~~
w  
Qiang Xue committed
117
	 * array(
Qiang Xue committed
118
	 *   // built-in "required" validator
Qiang Xue committed
119
	 *	 array('username', 'required'),
Qiang Xue committed
120
	 *   // built-in "length" validator customized with "min" and "max" properties
Qiang Xue committed
121
	 *	 array('username', 'length', 'min'=>3, 'max'=>12),
Qiang Xue committed
122
	 *   // built-in "compare" validator that is used in "register" scenario only
Qiang Xue committed
123
	 *	 array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
Qiang Xue committed
124
	 *   // an inline validator defined via the "authenticate()" method in the model class
Qiang Xue committed
125
	 *	 array('password', 'authenticate', 'on'=>'login'),
Qiang Xue committed
126 127
	 *   // a validator of class "CaptchaValidator"
	 *   array('captcha', 'CaptchaValidator'),
w  
Qiang Xue committed
128
	 * );
w  
Qiang Xue committed
129
	 * ~~~
w  
Qiang Xue committed
130 131
	 *
	 * Note, in order to inherit rules defined in the parent class, a child class needs to
w  
Qiang Xue committed
132
	 * merge the parent rules with child rules using functions such as `array_merge()`.
w  
Qiang Xue committed
133
	 *
w  
Qiang Xue committed
134
	 * @return array validation rules
w  
Qiang Xue committed
135 136 137 138 139 140 141 142
	 */
	public function rules()
	{
		return array();
	}

	/**
	 * Returns the attribute labels.
w  
Qiang Xue committed
143 144 145 146 147
	 *
	 * 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
148
	 * By default an attribute label is generated using [[generateAttributeLabel()]].
w  
Qiang Xue committed
149 150 151
	 * 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
152
	 * merge the parent labels with child labels using functions such as `array_merge()`.
w  
Qiang Xue committed
153 154 155 156 157 158 159 160 161 162
	 *
	 * @return array attribute labels (name=>label)
	 * @see generateAttributeLabel
	 */
	public function attributeLabels()
	{
		return array();
	}

	/**
w  
Qiang Xue committed
163
	 * Performs the data validation.
w  
Qiang Xue committed
164
	 *
Qiang Xue committed
165
	 * This method executes the validation rules as declared in [[rules()]].
w  
Qiang Xue committed
166 167
	 * 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
w  
Qiang Xue committed
168 169
	 * or contains the scenario.
	 *
Qiang Xue committed
170 171 172
	 * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
	 * after actual validation, respectively. If [[beforeValidate()]] returns false,
	 * the validation and [[afterValidate()]] will be cancelled.
w  
Qiang Xue committed
173
	 *
Qiang Xue committed
174
	 * Errors found during the validation can be retrieved via [[getErrors()]].
w  
Qiang Xue committed
175
	 *
w  
Qiang Xue committed
176 177 178
	 * @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
179
	 * @param boolean $clearErrors whether to call [[clearErrors()]] before performing validation
w  
Qiang Xue committed
180 181 182 183
	 * @return boolean whether the validation is successful without any error.
	 * @see beforeValidate
	 * @see afterValidate
	 */
w  
Qiang Xue committed
184
	public function validate($attributes = null, $clearErrors = true)
w  
Qiang Xue committed
185
	{
w  
Qiang Xue committed
186
		if ($clearErrors) {
w  
Qiang Xue committed
187
			$this->clearErrors();
w  
Qiang Xue committed
188 189
		}
		if ($this->beforeValidate()) {
w  
Qiang Xue committed
190
			foreach ($this->getActiveValidators() as $validator) {
w  
Qiang Xue committed
191 192
				$validator->validate($this, $attributes);
			}
w  
Qiang Xue committed
193 194 195
			$this->afterValidate();
			return !$this->hasErrors();
		}
w  
Qiang Xue committed
196
		return false;
w  
Qiang Xue committed
197 198 199 200
	}

	/**
	 * This method is invoked before validation starts.
w  
Qiang Xue committed
201
	 * The default implementation raises the [[onBeforeValidate]] event.
w  
Qiang Xue committed
202 203 204 205 206
	 * 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.
	 * @return boolean whether validation should be executed. Defaults to true.
	 * If false is returned, the validation will stop and the model is considered invalid.
	 */
w  
Qiang Xue committed
207
	public function beforeValidate()
w  
Qiang Xue committed
208
	{
w  
Qiang Xue committed
209
		if ($this->hasEventHandlers('onBeforeValidate')) {
Qiang Xue committed
210
			$event = new ModelEvent($this);
w  
Qiang Xue committed
211 212 213 214
			$this->onBeforeValidate($event);
			return $event->isValid;
		}
		return true;
w  
Qiang Xue committed
215 216 217 218
	}

	/**
	 * This method is invoked after validation ends.
w  
Qiang Xue committed
219
	 * The default implementation raises the [[onAfterValidate]] event.
w  
Qiang Xue committed
220 221 222
	 * 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
223
	public function afterValidate()
w  
Qiang Xue committed
224
	{
w  
Qiang Xue committed
225
		if ($this->hasEventHandlers('onAfterValidate')) {
w  
Qiang Xue committed
226
			$this->onAfterValidate(new Event($this));
w  
Qiang Xue committed
227
		}
w  
Qiang Xue committed
228 229 230 231
	}

	/**
	 * This event is raised before the validation is performed.
Qiang Xue committed
232
	 * @param ModelEvent $event the event parameter
w  
Qiang Xue committed
233 234 235
	 */
	public function onBeforeValidate($event)
	{
Qiang Xue committed
236
		$this->raiseEvent(__FUNCTION__, $event);
w  
Qiang Xue committed
237 238 239 240
	}

	/**
	 * This event is raised after the validation is performed.
w  
Qiang Xue committed
241
	 * @param Event $event the event parameter
w  
Qiang Xue committed
242 243 244
	 */
	public function onAfterValidate($event)
	{
Qiang Xue committed
245
		$this->raiseEvent(__FUNCTION__, $event);
w  
Qiang Xue committed
246 247 248
	}

	/**
Qiang Xue committed
249
	 * Returns all the validators declared in [[rules()]].
w  
Qiang Xue committed
250
	 *
Qiang Xue committed
251
	 * This method differs from [[getActiveValidators()]] in that the latter
w  
Qiang Xue committed
252 253 254 255 256 257
	 * 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
258
	 * ~~~
w  
Qiang Xue committed
259 260 261 262
	 * $model->validators->add($newValidator);
	 * ~~~
	 *
	 * @return Vector all the validators declared in the model.
w  
Qiang Xue committed
263
	 */
w  
Qiang Xue committed
264
	public function getValidators()
w  
Qiang Xue committed
265
	{
w  
Qiang Xue committed
266
		if ($this->_validators === null) {
w  
Qiang Xue committed
267
			$this->_validators = $this->createValidators();
w  
Qiang Xue committed
268
		}
w  
Qiang Xue committed
269 270 271 272
		return $this->_validators;
	}

	/**
w  
Qiang Xue committed
273 274
	 * 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
275
	 * If this is null, the validators for ALL attributes in the model will be returned.
Qiang Xue committed
276
	 * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
w  
Qiang Xue committed
277
	 */
w  
Qiang Xue committed
278
	public function getActiveValidators($attribute = null)
w  
Qiang Xue committed
279
	{
w  
Qiang Xue committed
280 281
		$validators = array();
		$scenario = $this->getScenario();
w  
Qiang Xue committed
282 283 284
		foreach ($this->getValidators() as $validator) {
			if ($validator->applyTo($scenario)) {
				if ($attribute === null || in_array($attribute, $validator->attributes, true)) {
w  
Qiang Xue committed
285
					$validators[] = $validator;
w  
Qiang Xue committed
286
				}
w  
Qiang Xue committed
287 288 289 290 291 292
			}
		}
		return $validators;
	}

	/**
Qiang Xue committed
293 294
	 * 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
295
	 * @return Vector validators
w  
Qiang Xue committed
296 297 298
	 */
	public function createValidators()
	{
w  
Qiang Xue committed
299 300
		$validators = new Vector;
		foreach ($this->rules() as $rule) {
Qiang Xue committed
301
			if (isset($rule[0], $rule[1])) { // attributes, validator type
w  
Qiang Xue committed
302 303
				$validator = \yii\validators\Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2));
				$validators->add($validator);
Qiang Xue committed
304
			} else {
w  
Qiang Xue committed
305
				throw new Exception('Invalid validation rule: a rule must specify both attribute names and validator type.');
w  
Qiang Xue committed
306
			}
w  
Qiang Xue committed
307 308 309 310 311 312 313
		}
		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
314
	 * [[\yii\validators\RequiredValidator|required]] validation rule in the
w  
Qiang Xue committed
315
	 * current [[scenario]].
w  
Qiang Xue committed
316 317 318 319 320
	 * @param string $attribute attribute name
	 * @return boolean whether the attribute is required
	 */
	public function isAttributeRequired($attribute)
	{
w  
Qiang Xue committed
321 322
		foreach ($this->getActiveValidators($attribute) as $validator) {
			if ($validator instanceof \yii\validators\RequiredValidator) {
w  
Qiang Xue committed
323
				return true;
w  
Qiang Xue committed
324
			}
w  
Qiang Xue committed
325 326 327 328 329 330 331 332 333 334 335
		}
		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)
	{
Qiang Xue committed
336
		$validators = $this->getActiveValidators($attribute);
w  
Qiang Xue committed
337 338 339 340 341 342
		foreach ($validators as $validator) {
			if (!$validator->safe) {
				return false;
			}
		}
		return $validators !== array();
w  
Qiang Xue committed
343 344 345 346 347 348 349 350 351 352 353
	}

	/**
	 * 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
354
		$labels = $this->attributeLabels();
Alex committed
355
		return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
w  
Qiang Xue committed
356 357 358 359 360 361 362
	}

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

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

	/**
	 * 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
401
	 * @see getErrors
w  
Qiang Xue committed
402 403 404 405 406 407 408 409 410 411 412
	 */
	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
413
	public function addError($attribute, $error)
w  
Qiang Xue committed
414
	{
w  
Qiang Xue committed
415
		$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
416 417 418 419 420 421 422 423 424 425
	}

	/**
	 * 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
426 427 428
		foreach ($errors as $attribute => $error) {
			if (is_array($error)) {
				foreach ($error as $e) {
w  
Qiang Xue committed
429
					$this->_errors[$attribute][] = $e;
w  
Qiang Xue committed
430
				}
Qiang Xue committed
431
			} else {
w  
Qiang Xue committed
432
				$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
433
			}
w  
Qiang Xue committed
434 435 436 437 438 439 440
		}
	}

	/**
	 * 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
441
	public function clearErrors($attribute = null)
w  
Qiang Xue committed
442
	{
w  
Qiang Xue committed
443
		if ($attribute === null) {
w  
Qiang Xue committed
444
			$this->_errors = array();
Qiang Xue committed
445
		} else {
w  
Qiang Xue committed
446
			unset($this->_errors[$attribute]);
w  
Qiang Xue committed
447
		}
w  
Qiang Xue committed
448 449 450
	}

	/**
w  
Qiang Xue committed
451 452
	 * 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
453
	 * changing the first letter of each word to upper case.
w  
Qiang Xue committed
454
	 * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
w  
Qiang Xue committed
455 456 457 458 459
	 * @param string $name the column name
	 * @return string the attribute label
	 */
	public function generateAttributeLabel($name)
	{
Qiang Xue committed
460
		return Text::camel2words($name, true);
w  
Qiang Xue committed
461 462 463
	}

	/**
w  
Qiang Xue committed
464
	 * Returns attribute values.
w  
Qiang Xue committed
465
	 * @param array $names list of attributes whose value needs to be returned.
Qiang Xue committed
466
	 * Defaults to null, meaning all attributes listed in [[attributeNames()]] will be returned.
w  
Qiang Xue committed
467 468 469
	 * If it is an array, only the attributes in the array will be returned.
	 * @return array attribute values (name=>value).
	 */
w  
Qiang Xue committed
470
	public function getAttributes($names = null)
w  
Qiang Xue committed
471
	{
w  
Qiang Xue committed
472
		$values = array();
w  
Qiang Xue committed
473

w  
Qiang Xue committed
474 475 476 477 478 479
		if (is_array($names)) {
			foreach ($this->attributeNames() as $name) {
				if (in_array($name, $names, true)) {
					$values[$name] = $this->$name;
				}
			}
Qiang Xue committed
480
		} else {
w  
Qiang Xue committed
481 482 483 484 485 486
			foreach ($this->attributeNames() as $name) {
				$values[$name] = $this->$name;
			}
		}

		return $values;
w  
Qiang Xue committed
487 488 489 490
	}

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

	/**
	 * 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
518
	public function onUnsafeAttribute($name, $value)
w  
Qiang Xue committed
519
	{
w  
Qiang Xue committed
520
		if (YII_DEBUG) {
Qiang Xue committed
521
			\Yii::warning("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.");
w  
Qiang Xue committed
522
		}
w  
Qiang Xue committed
523 524 525 526 527 528 529 530
	}

	/**
	 * Returns the scenario that this model is used in.
	 *
	 * Scenario affects how validation is performed and which attributes can
	 * be massively assigned.
	 *
w  
Qiang Xue committed
531
	 * A validation rule will be performed when calling [[validate]]
w  
Qiang Xue committed
532 533 534
	 * 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
w  
Qiang Xue committed
535 536 537
	 * a validation rule for the current scenario. An exception is
	 * the [[\yii\validators\UnsafeValidator|unsafe]] validator which marks
	 * the associated attributes as unsafe and not allowed to be massively assigned.
w  
Qiang Xue committed
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
	 *
	 * @return string the scenario that this model is in.
	 */
	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
553
		$this->_scenario = $value;
w  
Qiang Xue committed
554 555 556 557
	}

	/**
	 * Returns the attribute names that are safe to be massively assigned.
w  
Qiang Xue committed
558
	 * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
w  
Qiang Xue committed
559 560 561 562
	 * @return array safe attribute names
	 */
	public function getSafeAttributeNames()
	{
w  
Qiang Xue committed
563 564
		$attributes = array();
		$unsafe = array();
w  
Qiang Xue committed
565
		foreach ($this->getActiveValidators() as $validator) {
w  
Qiang Xue committed
566 567
			if (!$validator->safe) {
				foreach ($validator->attributes as $name) {
w  
Qiang Xue committed
568
					$unsafe[] = $name;
w  
Qiang Xue committed
569
				}
Qiang Xue committed
570
			} else {
w  
Qiang Xue committed
571
				foreach ($validator->attributes as $name) {
w  
Qiang Xue committed
572
					$attributes[$name] = true;
w  
Qiang Xue committed
573
				}
w  
Qiang Xue committed
574 575 576
			}
		}

w  
Qiang Xue committed
577
		foreach ($unsafe as $name) {
w  
Qiang Xue committed
578
			unset($attributes[$name]);
w  
Qiang Xue committed
579
		}
w  
Qiang Xue committed
580 581 582 583 584 585
		return array_keys($attributes);
	}

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

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

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

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