Model.php 21.4 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
 * - [[EVENT_BEFORE_VALIDATE]]: an event raised at the beginning of [[validate()]]
 * - [[EVENT_AFTER_VALIDATE]]: 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
 * @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.
 *
w  
Qiang Xue committed
41
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
42
 * @since 2.0
w  
Qiang Xue committed
43
 */
Qiang Xue committed
44
class Model extends Component implements \IteratorAggregate, \ArrayAccess
w  
Qiang Xue committed
45
{
46 47 48 49 50 51 52 53 54 55
	/**
	 * @event ModelEvent an event raised at the beginning of [[validate()]]. You may set
	 * [[ModelEvent::isValid]] to be false to stop the validation.
	 */
	const EVENT_BEFORE_VALIDATE = 'beforeValidate';
	/**
	 * @event Event an event raised at the end of [[validate()]]
	 */
	const EVENT_AFTER_VALIDATE = 'afterValidate';

Qiang Xue committed
56 57 58 59 60 61 62 63 64 65 66
	/**
	 * @var array validation errors (attribute name => array of errors)
	 */
	private $_errors;
	/**
	 * @var Vector vector of validators
	 */
	private $_validators;
	/**
	 * @var string current scenario
	 */
67
	private $_scenario = 'default';
w  
Qiang Xue committed
68 69 70 71

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

135
	/**
136
	 * Returns a list of scenarios and the corresponding active attributes.
Qiang Xue committed
137
	 * An active attribute is one that is subject to validation in the current scenario.
138 139 140 141 142 143 144 145 146 147
	 * The returned array should be in the following format:
	 *
	 * ~~~
	 * array(
	 *     'scenario1' => array('attribute11', 'attribute12', ...),
	 *     'scenario2' => array('attribute21', 'attribute22', ...),
	 *     ...
	 * )
	 * ~~~
	 *
Qiang Xue committed
148
	 * By default, an active attribute that is considered safe and can be massively assigned.
149
	 * If an attribute should NOT be massively assigned (thus considered unsafe),
Qiang Xue committed
150
	 * please prefix the attribute with an exclamation character (e.g. '!rank').
151
	 *
Qiang Xue committed
152 153 154 155 156
	 * 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.
157 158 159
	 */
	public function scenarios()
	{
Qiang Xue committed
160 161
		$attributes = array();
		foreach ($this->getActiveValidators() as $validator) {
Qiang Xue committed
162 163 164 165
			if ($validator->isActive('default')) {
				foreach ($validator->attributes as $name) {
					$attributes[$name] = true;
				}
Qiang Xue committed
166 167 168 169 170
			}
		}
		return array(
			'default' => array_keys($attributes),
		);
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	}

	/**
	 * 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()
	{
		$class = new \ReflectionClass($this);
		$names = array();
		foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
			$name = $property->getName();
			if (!$property->isStatic()) {
				$names[] = $name;
			}
		}
Qiang Xue committed
189
		return $names;
190 191
	}

w  
Qiang Xue committed
192 193
	/**
	 * Returns the attribute labels.
w  
Qiang Xue committed
194 195 196 197 198
	 *
	 * 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
199
	 * By default an attribute label is generated using [[generateAttributeLabel()]].
w  
Qiang Xue committed
200 201 202
	 * 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
203
	 * merge the parent labels with child labels using functions such as `array_merge()`.
w  
Qiang Xue committed
204 205 206 207 208 209 210 211 212 213
	 *
	 * @return array attribute labels (name=>label)
	 * @see generateAttributeLabel
	 */
	public function attributeLabels()
	{
		return array();
	}

	/**
w  
Qiang Xue committed
214
	 * Performs the data validation.
w  
Qiang Xue committed
215
	 *
216 217 218 219 220
	 * 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
221
	 *
Qiang Xue committed
222
	 * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
223 224
	 * after the actual validation, respectively. If [[beforeValidate()]] returns false,
	 * the validation will be cancelled and [[afterValidate()]] will not be called.
w  
Qiang Xue committed
225
	 *
226 227
	 * Errors found during the validation can be retrieved via [[getErrors()]]
	 * and [[getError()]].
w  
Qiang Xue committed
228
	 *
w  
Qiang Xue committed
229 230 231
	 * @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
232
	 * @param boolean $clearErrors whether to call [[clearErrors()]] before performing validation
w  
Qiang Xue committed
233 234
	 * @return boolean whether the validation is successful without any error.
	 */
w  
Qiang Xue committed
235
	public function validate($attributes = null, $clearErrors = true)
w  
Qiang Xue committed
236
	{
w  
Qiang Xue committed
237
		if ($clearErrors) {
w  
Qiang Xue committed
238
			$this->clearErrors();
w  
Qiang Xue committed
239
		}
240 241 242
		if ($attributes === null) {
			$attributes = $this->activeAttributes();
		}
w  
Qiang Xue committed
243
		if ($this->beforeValidate()) {
w  
Qiang Xue committed
244
			foreach ($this->getActiveValidators() as $validator) {
w  
Qiang Xue committed
245 246
				$validator->validate($this, $attributes);
			}
w  
Qiang Xue committed
247 248 249
			$this->afterValidate();
			return !$this->hasErrors();
		}
w  
Qiang Xue committed
250
		return false;
w  
Qiang Xue committed
251 252 253 254
	}

	/**
	 * This method is invoked before validation starts.
Qiang Xue committed
255
	 * The default implementation raises a `beforeValidate` event.
w  
Qiang Xue committed
256 257
	 * 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.
258
	 * @return boolean whether the validation should be executed. Defaults to true.
w  
Qiang Xue committed
259 260
	 * If false is returned, the validation will stop and the model is considered invalid.
	 */
w  
Qiang Xue committed
261
	public function beforeValidate()
w  
Qiang Xue committed
262
	{
Qiang Xue committed
263
		$event = new ModelEvent($this);
264
		$this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
Qiang Xue committed
265
		return $event->isValid;
w  
Qiang Xue committed
266 267 268 269
	}

	/**
	 * This method is invoked after validation ends.
Qiang Xue committed
270
	 * The default implementation raises an `afterValidate` event.
w  
Qiang Xue committed
271 272 273
	 * 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
274
	public function afterValidate()
w  
Qiang Xue committed
275
	{
276
		$this->trigger(self::EVENT_AFTER_VALIDATE);
w  
Qiang Xue committed
277 278 279
	}

	/**
Qiang Xue committed
280
	 * Returns all the validators declared in [[rules()]].
w  
Qiang Xue committed
281
	 *
Qiang Xue committed
282
	 * This method differs from [[getActiveValidators()]] in that the latter
w  
Qiang Xue committed
283 284 285 286 287 288
	 * 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
289
	 * ~~~
w  
Qiang Xue committed
290 291 292 293
	 * $model->validators->add($newValidator);
	 * ~~~
	 *
	 * @return Vector all the validators declared in the model.
w  
Qiang Xue committed
294
	 */
w  
Qiang Xue committed
295
	public function getValidators()
w  
Qiang Xue committed
296
	{
w  
Qiang Xue committed
297
		if ($this->_validators === null) {
w  
Qiang Xue committed
298
			$this->_validators = $this->createValidators();
w  
Qiang Xue committed
299
		}
w  
Qiang Xue committed
300 301 302 303
		return $this->_validators;
	}

	/**
w  
Qiang Xue committed
304 305
	 * 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
306
	 * If this is null, the validators for ALL attributes in the model will be returned.
Qiang Xue committed
307
	 * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
w  
Qiang Xue committed
308
	 */
w  
Qiang Xue committed
309
	public function getActiveValidators($attribute = null)
w  
Qiang Xue committed
310
	{
w  
Qiang Xue committed
311 312
		$validators = array();
		$scenario = $this->getScenario();
313
		/** @var $validator Validator */
w  
Qiang Xue committed
314
		foreach ($this->getValidators() as $validator) {
Qiang Xue committed
315
			if ($validator->isActive($scenario) && ($attribute === null || in_array($attribute, $validator->attributes, true))) {
Qiang Xue committed
316
				$validators[] = $validator;
w  
Qiang Xue committed
317 318 319 320 321 322
			}
		}
		return $validators;
	}

	/**
Qiang Xue committed
323 324
	 * 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
325
	 * @return Vector validators
Qiang Xue committed
326
	 * @throws InvalidConfigException if any validation rule configuration is invalid
w  
Qiang Xue committed
327 328 329
	 */
	public function createValidators()
	{
w  
Qiang Xue committed
330 331
		$validators = new Vector;
		foreach ($this->rules() as $rule) {
332 333 334 335
			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
336
				$validators->add($validator);
Qiang Xue committed
337
			} else {
Qiang Xue committed
338
				throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
w  
Qiang Xue committed
339
			}
w  
Qiang Xue committed
340 341 342 343 344 345 346
		}
		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
347
	 * [[\yii\validators\RequiredValidator|required]] validation rule in the
w  
Qiang Xue committed
348
	 * current [[scenario]].
w  
Qiang Xue committed
349 350 351 352 353
	 * @param string $attribute attribute name
	 * @return boolean whether the attribute is required
	 */
	public function isAttributeRequired($attribute)
	{
w  
Qiang Xue committed
354
		foreach ($this->getActiveValidators($attribute) as $validator) {
355
			if ($validator instanceof RequiredValidator) {
w  
Qiang Xue committed
356
				return true;
w  
Qiang Xue committed
357
			}
w  
Qiang Xue committed
358 359 360 361 362 363 364 365 366 367 368
		}
		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)
	{
369
		return in_array($attribute, $this->safeAttributes(), true);
w  
Qiang Xue committed
370 371 372 373 374 375 376 377 378 379 380
	}

	/**
	 * 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
381
		$labels = $this->attributeLabels();
Alex committed
382
		return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
w  
Qiang Xue committed
383 384 385 386
	}

	/**
	 * Returns a value indicating whether there is any validation error.
387
	 * @param string|null $attribute attribute name. Use null to check all attributes.
w  
Qiang Xue committed
388 389
	 * @return boolean whether there is any error.
	 */
w  
Qiang Xue committed
390
	public function hasErrors($attribute = null)
w  
Qiang Xue committed
391
	{
w  
Qiang Xue committed
392
		return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
w  
Qiang Xue committed
393 394 395 396 397 398
	}

	/**
	 * 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
399 400
	 * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
	 *
w  
Qiang Xue committed
401
	 * ~~~
w  
Qiang Xue committed
402
	 * array(
Qiang Xue committed
403 404 405 406 407 408 409
	 *     'username' => array(
	 *         'Username is required.',
	 *         'Username must contain only word characters.',
	 *     ),
	 *     'email' => array(
	 *         'Email address is invalid.',
	 *     )
w  
Qiang Xue committed
410 411 412 413
	 * )
	 * ~~~
	 *
	 * @see getError
w  
Qiang Xue committed
414
	 */
w  
Qiang Xue committed
415
	public function getErrors($attribute = null)
w  
Qiang Xue committed
416
	{
w  
Qiang Xue committed
417
		if ($attribute === null) {
w  
Qiang Xue committed
418
			return $this->_errors === null ? array() : $this->_errors;
Qiang Xue committed
419
		} else {
w  
Qiang Xue committed
420
			return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
w  
Qiang Xue committed
421
		}
w  
Qiang Xue committed
422 423 424 425 426 427
	}

	/**
	 * 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
428
	 * @see getErrors
w  
Qiang Xue committed
429 430 431 432 433 434 435 436 437 438 439
	 */
	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
440
	public function addError($attribute, $error)
w  
Qiang Xue committed
441
	{
w  
Qiang Xue committed
442
		$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
443 444 445 446 447 448 449 450 451 452
	}

	/**
	 * 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
453 454 455
		foreach ($errors as $attribute => $error) {
			if (is_array($error)) {
				foreach ($error as $e) {
w  
Qiang Xue committed
456
					$this->_errors[$attribute][] = $e;
w  
Qiang Xue committed
457
				}
Qiang Xue committed
458
			} else {
w  
Qiang Xue committed
459
				$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
460
			}
w  
Qiang Xue committed
461 462 463 464 465 466 467
		}
	}

	/**
	 * 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
468
	public function clearErrors($attribute = null)
w  
Qiang Xue committed
469
	{
w  
Qiang Xue committed
470
		if ($attribute === null) {
w  
Qiang Xue committed
471
			$this->_errors = array();
Qiang Xue committed
472
		} else {
w  
Qiang Xue committed
473
			unset($this->_errors[$attribute]);
w  
Qiang Xue committed
474
		}
w  
Qiang Xue committed
475 476 477
	}

	/**
w  
Qiang Xue committed
478 479
	 * 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
480
	 * changing the first letter of each word to upper case.
w  
Qiang Xue committed
481
	 * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
w  
Qiang Xue committed
482 483 484 485 486
	 * @param string $name the column name
	 * @return string the attribute label
	 */
	public function generateAttributeLabel($name)
	{
Qiang Xue committed
487
		return StringHelper::camel2words($name, true);
w  
Qiang Xue committed
488 489 490
	}

	/**
w  
Qiang Xue committed
491
	 * Returns attribute values.
w  
Qiang Xue committed
492
	 * @param array $names list of attributes whose value needs to be returned.
493
	 * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
w  
Qiang Xue committed
494
	 * If it is an array, only the attributes in the array will be returned.
495
	 * @param array $except list of attributes whose value should NOT be returned.
w  
Qiang Xue committed
496 497
	 * @return array attribute values (name=>value).
	 */
498
	public function getAttributes($names = null, $except = array())
w  
Qiang Xue committed
499
	{
w  
Qiang Xue committed
500
		$values = array();
501 502 503 504 505 506 507 508
		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
509 510 511
		}

		return $values;
w  
Qiang Xue committed
512 513 514 515
	}

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

	/**
	 * 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
543
	public function onUnsafeAttribute($name, $value)
w  
Qiang Xue committed
544
	{
w  
Qiang Xue committed
545
		if (YII_DEBUG) {
Qiang Xue committed
546
			\Yii::warning("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.");
w  
Qiang Xue committed
547
		}
w  
Qiang Xue committed
548 549 550 551 552 553 554 555
	}

	/**
	 * Returns the scenario that this model is used in.
	 *
	 * Scenario affects how validation is performed and which attributes can
	 * be massively assigned.
	 *
556
	 * @return string the scenario that this model is in. Defaults to 'default'.
w  
Qiang Xue committed
557 558 559 560 561 562 563 564 565 566 567 568 569
	 */
	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
570
		$this->_scenario = $value;
w  
Qiang Xue committed
571 572 573
	}

	/**
574
	 * Returns the attribute names that are safe to be massively assigned in the current scenario.
w  
Qiang Xue committed
575 576
	 * @return array safe attribute names
	 */
577
	public function safeAttributes()
w  
Qiang Xue committed
578
	{
579
		$scenario = $this->getScenario();
580
		$scenarios = $this->scenarios();
Qiang Xue committed
581
		$attributes = array();
582 583 584 585 586
		if (isset($scenarios[$scenario])) {
			foreach ($scenarios[$scenario] as $attribute) {
				if ($attribute[0] !== '!') {
					$attributes[] = $attribute;
				}
w  
Qiang Xue committed
587 588
			}
		}
Qiang Xue committed
589
		return $attributes;
590
	}
w  
Qiang Xue committed
591

592 593 594 595 596 597
	/**
	 * Returns the attribute names that are subject to validation in the current scenario.
	 * @return array safe attribute names
	 */
	public function activeAttributes()
	{
598
		$scenario = $this->getScenario();
599
		$scenarios = $this->scenarios();
600 601 602 603 604 605 606
		if (isset($scenarios[$scenario])) {
			$attributes = $scenarios[$this->getScenario()];
			foreach ($attributes as $i => $attribute) {
				if ($attribute[0] === '!') {
					$attributes[$i] = substr($attribute, 1);
				}
			}
Qiang Xue committed
607
			return $attributes;
608
		} else {
Qiang Xue committed
609
			return array();
w  
Qiang Xue committed
610
		}
w  
Qiang Xue committed
611 612 613 614 615
	}

	/**
	 * Returns an iterator for traversing the attributes in the model.
	 * This method is required by the interface IteratorAggregate.
Qiang Xue committed
616
	 * @return DictionaryIterator an iterator for traversing the items in the list.
w  
Qiang Xue committed
617 618 619
	 */
	public function getIterator()
	{
w  
Qiang Xue committed
620 621
		$attributes = $this->getAttributes();
		return new DictionaryIterator($attributes);
w  
Qiang Xue committed
622 623 624 625
	}

	/**
	 * Returns whether there is an element at the specified offset.
w  
Qiang Xue committed
626 627
	 * 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
628 629 630 631 632
	 * @param mixed $offset the offset to check on
	 * @return boolean
	 */
	public function offsetExists($offset)
	{
Qiang Xue committed
633
		return $this->$offset !== null;
w  
Qiang Xue committed
634 635 636 637
	}

	/**
	 * Returns the element at the specified offset.
w  
Qiang Xue committed
638 639
	 * 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
640
	 * @param mixed $offset the offset to retrieve element.
w  
Qiang Xue committed
641 642 643 644 645 646 647 648 649
	 * @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
650 651
	 * 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
652 653 654
	 * @param integer $offset the offset to set element
	 * @param mixed $item the element value
	 */
w  
Qiang Xue committed
655
	public function offsetSet($offset, $item)
w  
Qiang Xue committed
656
	{
w  
Qiang Xue committed
657
		$this->$offset = $item;
w  
Qiang Xue committed
658 659 660 661
	}

	/**
	 * Unsets the element at the specified offset.
w  
Qiang Xue committed
662 663
	 * 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
664 665 666 667 668 669 670
	 * @param mixed $offset the offset to unset element
	 */
	public function offsetUnset($offset)
	{
		unset($this->$offset);
	}
}