Model.php 20.2 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;
Qiang Xue committed
13

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
 * 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
25
 * Model also raises the following events when performing data validation:
w  
Qiang Xue committed
26
 *
Qiang Xue committed
27 28
 * - [[beforeValidate]]: an event raised at the beginning of [[validate()]]
 * - [[afterValidate]]: 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
 *
Qiang Xue committed
33 34 35 36 37 38 39 40 41 42 43
 * @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.
 * @property array $safeAttributeNames Safe attribute names in the current [[scenario]].
 *
 * @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
44
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
45
 * @since 2.0
w  
Qiang Xue committed
46
 */
Qiang Xue committed
47
class Model extends Component implements \IteratorAggregate, \ArrayAccess
w  
Qiang Xue committed
48
{
w  
Qiang Xue committed
49
	private static $_attributes = array(); // class name => array of attribute names
Qiang Xue committed
50 51 52
	private $_errors; // attribute name => array of errors
	private $_validators; // validators
	private $_scenario; // scenario
w  
Qiang Xue committed
53 54 55

	/**
	 * Constructor.
Qiang Xue committed
56
	 * @param string|null $scenario name of the [[scenario]] that this model is used in.
w  
Qiang Xue committed
57
	 */
Qiang Xue committed
58
	public function __construct($scenario = null)
w  
Qiang Xue committed
59 60 61 62
	{
		$this->_scenario = $scenario;
	}

w  
Qiang Xue committed
63
	/**
w  
Qiang Xue committed
64 65
	 * Returns the list of attribute names.
	 * By default, this method returns all public non-static properties of the class.
Qiang Xue committed
66
	 * You may override this method to change the default behavior.
w  
Qiang Xue committed
67 68
	 * @return array list of attribute names.
	 */
w  
Qiang Xue committed
69 70 71 72 73 74 75
	public function attributeNames()
	{
		$className = get_class($this);
		if (isset(self::$_attributes[$className])) {
			return self::$_attributes[$className];
		}

w  
Qiang Xue committed
76
		$class = new \ReflectionClass($this);
w  
Qiang Xue committed
77
		$names = array();
w  
Qiang Xue committed
78
		foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
w  
Qiang Xue committed
79
			$name = $property->getName();
w  
Qiang Xue committed
80
			if (!$property->isStatic()) {
w  
Qiang Xue committed
81 82 83 84 85
				$names[] = $name;
			}
		}
		return self::$_attributes[$className] = $names;
	}
w  
Qiang Xue committed
86 87 88 89

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

	/**
	 * Returns the attribute labels.
w  
Qiang Xue committed
154 155 156 157 158
	 *
	 * 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
159
	 * By default an attribute label is generated using [[generateAttributeLabel()]].
w  
Qiang Xue committed
160 161 162
	 * 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
163
	 * merge the parent labels with child labels using functions such as `array_merge()`.
w  
Qiang Xue committed
164 165 166 167 168 169 170 171 172 173
	 *
	 * @return array attribute labels (name=>label)
	 * @see generateAttributeLabel
	 */
	public function attributeLabels()
	{
		return array();
	}

	/**
w  
Qiang Xue committed
174
	 * Performs the data validation.
w  
Qiang Xue committed
175
	 *
Qiang Xue committed
176
	 * This method executes the validation rules as declared in [[rules()]].
w  
Qiang Xue committed
177 178
	 * 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
179 180
	 * or contains the scenario.
	 *
Qiang Xue committed
181 182 183
	 * 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
184
	 *
Qiang Xue committed
185
	 * Errors found during the validation can be retrieved via [[getErrors()]].
w  
Qiang Xue committed
186
	 *
w  
Qiang Xue committed
187 188 189
	 * @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
190
	 * @param boolean $clearErrors whether to call [[clearErrors()]] before performing validation
w  
Qiang Xue committed
191
	 * @return boolean whether the validation is successful without any error.
Qiang Xue committed
192 193
	 * @see beforeValidate()
	 * @see afterValidate()
w  
Qiang Xue committed
194
	 */
w  
Qiang Xue committed
195
	public function validate($attributes = null, $clearErrors = true)
w  
Qiang Xue committed
196
	{
w  
Qiang Xue committed
197
		if ($clearErrors) {
w  
Qiang Xue committed
198
			$this->clearErrors();
w  
Qiang Xue committed
199 200
		}
		if ($this->beforeValidate()) {
w  
Qiang Xue committed
201
			foreach ($this->getActiveValidators() as $validator) {
w  
Qiang Xue committed
202 203
				$validator->validate($this, $attributes);
			}
w  
Qiang Xue committed
204 205 206
			$this->afterValidate();
			return !$this->hasErrors();
		}
w  
Qiang Xue committed
207
		return false;
w  
Qiang Xue committed
208 209 210 211
	}

	/**
	 * This method is invoked before validation starts.
Qiang Xue committed
212
	 * The default implementation raises a `beforeValidate` event.
w  
Qiang Xue committed
213 214 215 216 217
	 * 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
218
	public function beforeValidate()
w  
Qiang Xue committed
219
	{
Qiang Xue committed
220 221 222
		$event = new ModelEvent($this);
		$this->trigger('beforeValidate', $event);
		return $event->isValid;
w  
Qiang Xue committed
223 224 225 226
	}

	/**
	 * This method is invoked after validation ends.
Qiang Xue committed
227
	 * The default implementation raises an `afterValidate` event.
w  
Qiang Xue committed
228 229 230
	 * 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
231
	public function afterValidate()
w  
Qiang Xue committed
232
	{
Qiang Xue committed
233
		$this->trigger('afterValidate');
w  
Qiang Xue committed
234 235 236
	}

	/**
Qiang Xue committed
237
	 * Returns all the validators declared in [[rules()]].
w  
Qiang Xue committed
238
	 *
Qiang Xue committed
239
	 * This method differs from [[getActiveValidators()]] in that the latter
w  
Qiang Xue committed
240 241 242 243 244 245
	 * 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
246
	 * ~~~
w  
Qiang Xue committed
247 248 249 250
	 * $model->validators->add($newValidator);
	 * ~~~
	 *
	 * @return Vector all the validators declared in the model.
w  
Qiang Xue committed
251
	 */
w  
Qiang Xue committed
252
	public function getValidators()
w  
Qiang Xue committed
253
	{
w  
Qiang Xue committed
254
		if ($this->_validators === null) {
w  
Qiang Xue committed
255
			$this->_validators = $this->createValidators();
w  
Qiang Xue committed
256
		}
w  
Qiang Xue committed
257 258 259 260
		return $this->_validators;
	}

	/**
w  
Qiang Xue committed
261 262
	 * 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
263
	 * If this is null, the validators for ALL attributes in the model will be returned.
Qiang Xue committed
264
	 * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
w  
Qiang Xue committed
265
	 */
w  
Qiang Xue committed
266
	public function getActiveValidators($attribute = null)
w  
Qiang Xue committed
267
	{
w  
Qiang Xue committed
268 269
		$validators = array();
		$scenario = $this->getScenario();
w  
Qiang Xue committed
270
		foreach ($this->getValidators() as $validator) {
Qiang Xue committed
271 272
			if ($validator->applyTo($scenario, $attribute)) {
				$validators[] = $validator;
w  
Qiang Xue committed
273 274 275 276 277 278
			}
		}
		return $validators;
	}

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

	/**
	 * 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
340
		$labels = $this->attributeLabels();
Alex committed
341
		return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
w  
Qiang Xue committed
342 343 344 345 346 347 348
	}

	/**
	 * 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
349
	public function hasErrors($attribute = null)
w  
Qiang Xue committed
350
	{
w  
Qiang Xue committed
351
		return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
w  
Qiang Xue committed
352 353 354 355 356 357
	}

	/**
	 * 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
358 359
	 * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
	 *
w  
Qiang Xue committed
360
	 * ~~~
w  
Qiang Xue committed
361
	 * array(
Qiang Xue committed
362 363 364 365 366 367 368
	 *	 'username' => array(
	 *		 'Username is required.',
	 *		 'Username must contain only word characters.',
	 *	 ),
	 *	 'email' => array(
	 *		 'Email address is invalid.',
	 *	 )
w  
Qiang Xue committed
369 370 371 372
	 * )
	 * ~~~
	 *
	 * @see getError
w  
Qiang Xue committed
373
	 */
w  
Qiang Xue committed
374
	public function getErrors($attribute = null)
w  
Qiang Xue committed
375
	{
w  
Qiang Xue committed
376
		if ($attribute === null) {
w  
Qiang Xue committed
377
			return $this->_errors === null ? array() : $this->_errors;
Qiang Xue committed
378
		} else {
w  
Qiang Xue committed
379
			return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
w  
Qiang Xue committed
380
		}
w  
Qiang Xue committed
381 382 383 384 385 386
	}

	/**
	 * 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
387
	 * @see getErrors
w  
Qiang Xue committed
388 389 390 391 392 393 394 395 396 397 398
	 */
	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
399
	public function addError($attribute, $error)
w  
Qiang Xue committed
400
	{
w  
Qiang Xue committed
401
		$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
402 403 404 405 406 407 408 409 410 411
	}

	/**
	 * 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
412 413 414
		foreach ($errors as $attribute => $error) {
			if (is_array($error)) {
				foreach ($error as $e) {
w  
Qiang Xue committed
415
					$this->_errors[$attribute][] = $e;
w  
Qiang Xue committed
416
				}
Qiang Xue committed
417
			} else {
w  
Qiang Xue committed
418
				$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
419
			}
w  
Qiang Xue committed
420 421 422 423 424 425 426
		}
	}

	/**
	 * 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
427
	public function clearErrors($attribute = null)
w  
Qiang Xue committed
428
	{
w  
Qiang Xue committed
429
		if ($attribute === null) {
w  
Qiang Xue committed
430
			$this->_errors = array();
Qiang Xue committed
431
		} else {
w  
Qiang Xue committed
432
			unset($this->_errors[$attribute]);
w  
Qiang Xue committed
433
		}
w  
Qiang Xue committed
434 435 436
	}

	/**
w  
Qiang Xue committed
437 438
	 * 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
439
	 * changing the first letter of each word to upper case.
w  
Qiang Xue committed
440
	 * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
w  
Qiang Xue committed
441 442 443 444 445
	 * @param string $name the column name
	 * @return string the attribute label
	 */
	public function generateAttributeLabel($name)
	{
Qiang Xue committed
446
		return StringHelper::camel2words($name, true);
w  
Qiang Xue committed
447 448 449
	}

	/**
w  
Qiang Xue committed
450
	 * Returns attribute values.
w  
Qiang Xue committed
451
	 * @param array $names list of attributes whose value needs to be returned.
Qiang Xue committed
452
	 * Defaults to null, meaning all attributes listed in [[attributeNames()]] will be returned.
w  
Qiang Xue committed
453 454 455
	 * If it is an array, only the attributes in the array will be returned.
	 * @return array attribute values (name=>value).
	 */
w  
Qiang Xue committed
456
	public function getAttributes($names = null)
w  
Qiang Xue committed
457
	{
w  
Qiang Xue committed
458
		$values = array();
w  
Qiang Xue committed
459

w  
Qiang Xue committed
460 461 462 463 464 465
		if (is_array($names)) {
			foreach ($this->attributeNames() as $name) {
				if (in_array($name, $names, true)) {
					$values[$name] = $this->$name;
				}
			}
Qiang Xue committed
466
		} else {
w  
Qiang Xue committed
467 468 469 470 471 472
			foreach ($this->attributeNames() as $name) {
				$values[$name] = $this->$name;
			}
		}

		return $values;
w  
Qiang Xue committed
473 474 475 476
	}

	/**
	 * Sets the attribute values in a massive way.
w  
Qiang Xue committed
477
	 * @param array $values attribute values (name=>value) to be assigned to the model.
w  
Qiang Xue committed
478
	 * @param boolean $safeOnly whether the assignments should only be done to the safe attributes.
w  
Qiang Xue committed
479
	 * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
w  
Qiang Xue committed
480 481 482
	 * @see getSafeAttributeNames
	 * @see attributeNames
	 */
w  
Qiang Xue committed
483
	public function setAttributes($values, $safeOnly = true)
w  
Qiang Xue committed
484
	{
w  
Qiang Xue committed
485 486 487 488 489
		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
490
				} elseif ($safeOnly) {
w  
Qiang Xue committed
491 492 493
					$this->onUnsafeAttribute($name, $value);
				}
			}
w  
Qiang Xue committed
494 495 496 497 498 499 500 501 502 503
		}
	}

	/**
	 * 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
504
	public function onUnsafeAttribute($name, $value)
w  
Qiang Xue committed
505
	{
w  
Qiang Xue committed
506
		if (YII_DEBUG) {
Qiang Xue committed
507
			\Yii::warning("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.");
w  
Qiang Xue committed
508
		}
w  
Qiang Xue committed
509 510 511 512 513 514 515 516
	}

	/**
	 * Returns the scenario that this model is used in.
	 *
	 * Scenario affects how validation is performed and which attributes can
	 * be massively assigned.
	 *
Qiang Xue committed
517
	 * A validation rule will be performed when calling [[validate()]]
w  
Qiang Xue committed
518 519 520
	 * 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
521 522 523
	 * 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
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
	 *
	 * @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
539
		$this->_scenario = $value;
w  
Qiang Xue committed
540 541 542 543
	}

	/**
	 * Returns the attribute names that are safe to be massively assigned.
w  
Qiang Xue committed
544
	 * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
w  
Qiang Xue committed
545 546 547 548
	 * @return array safe attribute names
	 */
	public function getSafeAttributeNames()
	{
w  
Qiang Xue committed
549 550
		$attributes = array();
		$unsafe = array();
w  
Qiang Xue committed
551
		foreach ($this->getActiveValidators() as $validator) {
w  
Qiang Xue committed
552 553
			if (!$validator->safe) {
				foreach ($validator->attributes as $name) {
w  
Qiang Xue committed
554
					$unsafe[] = $name;
w  
Qiang Xue committed
555
				}
Qiang Xue committed
556
			} else {
w  
Qiang Xue committed
557
				foreach ($validator->attributes as $name) {
w  
Qiang Xue committed
558
					$attributes[$name] = true;
w  
Qiang Xue committed
559
				}
w  
Qiang Xue committed
560 561 562
			}
		}

w  
Qiang Xue committed
563
		foreach ($unsafe as $name) {
w  
Qiang Xue committed
564
			unset($attributes[$name]);
w  
Qiang Xue committed
565
		}
w  
Qiang Xue committed
566 567 568 569 570 571
		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
572
	 * @return DictionaryIterator an iterator for traversing the items in the list.
w  
Qiang Xue committed
573 574 575
	 */
	public function getIterator()
	{
w  
Qiang Xue committed
576 577
		$attributes = $this->getAttributes();
		return new DictionaryIterator($attributes);
w  
Qiang Xue committed
578 579 580 581
	}

	/**
	 * Returns whether there is an element at the specified offset.
w  
Qiang Xue committed
582 583
	 * 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
584 585 586 587 588
	 * @param mixed $offset the offset to check on
	 * @return boolean
	 */
	public function offsetExists($offset)
	{
w  
Qiang Xue committed
589
		return property_exists($this, $offset) && $this->$offset !== null;
w  
Qiang Xue committed
590 591 592 593
	}

	/**
	 * Returns the element at the specified offset.
w  
Qiang Xue committed
594 595
	 * 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
596
	 * @param mixed $offset the offset to retrieve element.
w  
Qiang Xue committed
597 598 599 600 601 602 603 604 605
	 * @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
606 607
	 * 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
608 609 610
	 * @param integer $offset the offset to set element
	 * @param mixed $item the element value
	 */
w  
Qiang Xue committed
611
	public function offsetSet($offset, $item)
w  
Qiang Xue committed
612
	{
w  
Qiang Xue committed
613
		$this->$offset = $item;
w  
Qiang Xue committed
614 615 616 617
	}

	/**
	 * Unsets the element at the specified offset.
w  
Qiang Xue committed
618 619
	 * 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
620 621 622 623 624 625 626
	 * @param mixed $offset the offset to unset element
	 */
	public function offsetUnset($offset)
	{
		unset($this->$offset);
	}
}