Model.php 21.8 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 12

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

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

w  
Qiang Xue committed
51 52 53
	/**
	 * Initializes this model.
	 *
Qiang Xue committed
54
	 * This method is required by the [[Initable]] interface. It is invoked by [[\Yii::createObject]]
mdomba (mdlap) committed
55
	 * after it creates the new model instance and initializes the model properties.
w  
Qiang Xue committed
56 57 58 59 60 61 62 63
	 *
	 * The default implementation calls [[behaviors]] and registers any available behaviors.
	 * You may override this method with additional initialization logic (e.g. establish DB connection).
	 * Make sure you call the parent implementation.
	 */
	public function init()
	{
		$this->attachBehaviors($this->behaviors());
Qiang Xue committed
64
		$this->afterInit();
w  
Qiang Xue committed
65 66 67 68 69 70 71 72 73 74
	}

	/**
	 * Returns a list of behaviors that this model should behave as.
	 * The return value should be an array of behavior configurations indexed by
	 * behavior names. Each behavior configuration can be either a string specifying
	 * the behavior class or an array of the following structure:
	 *
	 * ~~~
	 * 'behaviorName' => array(
Qiang Xue committed
75 76 77
	 *	 'class' => 'BehaviorClass',
	 *	 'property1' => 'value1',
	 *	 'property2' => 'value2',
w  
Qiang Xue committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91
	 * )
	 * ~~~
	 *
	 * Note that a behavior class must extend from [[Behavior]]. Behaviors declared
	 * in this method will be attached to the model when [[init]] is invoked.
	 *
	 * @return array the behavior configurations.
	 * @see init
	 */
	public function behaviors()
	{
		return array();
	}

w  
Qiang Xue committed
92
	/**
w  
Qiang Xue committed
93 94 95
	 * 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.
w  
Qiang Xue committed
96 97
	 * @return array list of attribute names.
	 */
w  
Qiang Xue committed
98 99 100 101 102 103 104
	public function attributeNames()
	{
		$className = get_class($this);
		if (isset(self::$_attributes[$className])) {
			return self::$_attributes[$className];
		}

w  
Qiang Xue committed
105
		$class = new \ReflectionClass($this);
w  
Qiang Xue committed
106
		$names = array();
w  
Qiang Xue committed
107
		foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
w  
Qiang Xue committed
108
			$name = $property->getName();
w  
Qiang Xue committed
109
			if (!$property->isStatic()) {
w  
Qiang Xue committed
110 111 112 113 114
				$names[] = $name;
			}
		}
		return self::$_attributes[$className] = $names;
	}
w  
Qiang Xue committed
115 116 117 118

	/**
	 * Returns the validation rules for attributes.
	 *
w  
Qiang Xue committed
119
	 * Validation rules are used by [[validate]] to check if attribute values are valid.
w  
Qiang Xue committed
120 121
	 * Child classes may override this method to declare different validation rules.
	 *
w  
Qiang Xue committed
122
	 * Each rule is an array with the following structure:
w  
Qiang Xue committed
123
	 *
w  
Qiang Xue committed
124
	 * ~~~
w  
Qiang Xue committed
125
	 * array(
Qiang Xue committed
126 127 128 129
	 *	 'attribute list',
	 *	 'validator type',
	 *	 'on'=>'scenario name',
	 *	 ...other parameters...
w  
Qiang Xue committed
130 131 132
	 * )
	 * ~~~
	 *
w  
Qiang Xue committed
133
	 * where
w  
Qiang Xue committed
134 135 136
	 *
	 *  - 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
137
	 *	class method, the name of a built-in validator, or a validator class (or its path alias).
w  
Qiang Xue committed
138
	 *  - on: optional, specifies the [[scenario|scenarios]] (separated by commas) when the validation
Qiang Xue committed
139
	 *	rule can be applied. If this option is not set, the rule will apply to all scenarios.
w  
Qiang Xue committed
140
	 *  - additional name-value pairs can be specified to initialize the corresponding validator properties.
Qiang Xue committed
141
	 *	Please refer to individual validator class API for possible properties.
w  
Qiang Xue committed
142 143 144 145
	 *
	 * A validator can be either a model class method or an object.
	 * If the former, the method must have the following signature:
	 *
w  
Qiang Xue committed
146
	 * ~~~
w  
Qiang Xue committed
147
	 * // $params refers to validation parameters given in the rule
w  
Qiang Xue committed
148 149 150 151 152 153
	 * function validatorName($attribute, $params)
	 * ~~~
	 *
	 * If the latter, the object must be extending from [[\yii\validators\Validator]].
	 * Yii provides a set of [[\yii\validators\Validator::builtInValidators|built-in validators]].
	 * They each have an alias name which can be used when specifying a validation rule.
w  
Qiang Xue committed
154 155
	 *
	 * The following are some examples:
w  
Qiang Xue committed
156
	 *
w  
Qiang Xue committed
157
	 * ~~~
w  
Qiang Xue committed
158
	 * array(
Qiang Xue committed
159 160 161 162
	 *	 array('username', 'required'),
	 *	 array('username', 'length', 'min'=>3, 'max'=>12),
	 *	 array('password', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),
	 *	 array('password', 'authenticate', 'on'=>'login'),
w  
Qiang Xue committed
163
	 * );
w  
Qiang Xue committed
164
	 * ~~~
w  
Qiang Xue committed
165 166
	 *
	 * Note, in order to inherit rules defined in the parent class, a child class needs to
w  
Qiang Xue committed
167
	 * merge the parent rules with child rules using functions such as `array_merge()`.
w  
Qiang Xue committed
168
	 *
w  
Qiang Xue committed
169
	 * @return array validation rules
w  
Qiang Xue committed
170 171 172 173 174 175 176 177
	 */
	public function rules()
	{
		return array();
	}

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

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

	/**
Qiang Xue committed
235 236
	 * This method is invoked at the end of [[init()]].
	 * The default implementation raises the [[onAfterInit]] event.
w  
Qiang Xue committed
237 238 239
	 * You may override this method to do postprocessing after model creation.
	 * Make sure you call the parent implementation so that the event is raised properly.
	 */
Qiang Xue committed
240
	public function afterInit()
w  
Qiang Xue committed
241
	{
Qiang Xue committed
242 243
		if ($this->hasEventHandlers('onAfterInit')) {
			$this->onAfterInit(new Event($this));
w  
Qiang Xue committed
244
		}
w  
Qiang Xue committed
245 246 247 248
	}

	/**
	 * This method is invoked before validation starts.
w  
Qiang Xue committed
249
	 * The default implementation raises the [[onBeforeValidate]] event.
w  
Qiang Xue committed
250 251 252 253 254
	 * 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
255
	public function beforeValidate()
w  
Qiang Xue committed
256
	{
w  
Qiang Xue committed
257
		if ($this->hasEventHandlers('onBeforeValidate')) {
w  
Qiang Xue committed
258
			$event = new ValidationEvent($this);
w  
Qiang Xue committed
259 260 261 262
			$this->onBeforeValidate($event);
			return $event->isValid;
		}
		return true;
w  
Qiang Xue committed
263 264 265 266
	}

	/**
	 * This method is invoked after validation ends.
w  
Qiang Xue committed
267
	 * The default implementation raises the [[onAfterValidate]] event.
w  
Qiang Xue committed
268 269 270
	 * 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
271
	public function afterValidate()
w  
Qiang Xue committed
272
	{
w  
Qiang Xue committed
273
		if ($this->hasEventHandlers('onAfterValidate')) {
w  
Qiang Xue committed
274
			$this->onAfterValidate(new Event($this));
w  
Qiang Xue committed
275
		}
w  
Qiang Xue committed
276 277
	}

w  
Qiang Xue committed
278 279 280 281 282 283
	/**
	 * This event is raised by [[init]] when initializing the model.
	 * @param Event $event the event parameter
	 */
	public function onInit($event)
	{
Qiang Xue committed
284
		$this->raiseEvent(__FUNCTION__, $event);
w  
Qiang Xue committed
285 286
	}

w  
Qiang Xue committed
287
	/**
Qiang Xue committed
288
	 * This event is raised at the end of [[init()]].
w  
Qiang Xue committed
289
	 * @param Event $event the event parameter
w  
Qiang Xue committed
290
	 */
Qiang Xue committed
291
	public function onAfterInit($event)
w  
Qiang Xue committed
292
	{
Qiang Xue committed
293
		$this->raiseEvent(__FUNCTION__, $event);
w  
Qiang Xue committed
294 295 296 297
	}

	/**
	 * This event is raised before the validation is performed.
w  
Qiang Xue committed
298
	 * @param ValidationEvent $event the event parameter
w  
Qiang Xue committed
299 300 301
	 */
	public function onBeforeValidate($event)
	{
Qiang Xue committed
302
		$this->raiseEvent(__FUNCTION__, $event);
w  
Qiang Xue committed
303 304 305 306
	}

	/**
	 * This event is raised after the validation is performed.
w  
Qiang Xue committed
307
	 * @param Event $event the event parameter
w  
Qiang Xue committed
308 309 310
	 */
	public function onAfterValidate($event)
	{
Qiang Xue committed
311
		$this->raiseEvent(__FUNCTION__, $event);
w  
Qiang Xue committed
312 313 314
	}

	/**
w  
Qiang Xue committed
315 316 317 318 319 320 321 322 323
	 * Returns all the validators declared in [[rules]].
	 *
	 * This method differs from [[getActiveValidators]] in that the latter
	 * 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
324
	 * ~~~
w  
Qiang Xue committed
325 326 327 328
	 * $model->validators->add($newValidator);
	 * ~~~
	 *
	 * @return Vector all the validators declared in the model.
w  
Qiang Xue committed
329
	 */
w  
Qiang Xue committed
330
	public function getValidators()
w  
Qiang Xue committed
331
	{
w  
Qiang Xue committed
332
		if ($this->_validators === null) {
w  
Qiang Xue committed
333
			$this->_validators = $this->createValidators();
w  
Qiang Xue committed
334
		}
w  
Qiang Xue committed
335 336 337 338
		return $this->_validators;
	}

	/**
w  
Qiang Xue committed
339 340
	 * 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
341
	 * If this is null, the validators for ALL attributes in the model will be returned.
w  
Qiang Xue committed
342
	 * @return array the validators applicable to the current [[scenario]].
w  
Qiang Xue committed
343
	 */
w  
Qiang Xue committed
344
	public function getActiveValidators($attribute = null)
w  
Qiang Xue committed
345
	{
w  
Qiang Xue committed
346 347
		$validators = array();
		$scenario = $this->getScenario();
w  
Qiang Xue committed
348 349 350
		foreach ($this->getValidators() as $validator) {
			if ($validator->applyTo($scenario)) {
				if ($attribute === null || in_array($attribute, $validator->attributes, true)) {
w  
Qiang Xue committed
351
					$validators[] = $validator;
w  
Qiang Xue committed
352
				}
w  
Qiang Xue committed
353 354 355 356 357 358
			}
		}
		return $validators;
	}

	/**
w  
Qiang Xue committed
359 360 361
	 * Creates validator objects based on the validation rules specified in [[rules]].
	 * Unlike [[getValidators]], calling this method each time, it will return a new list of validators.
	 * @return Vector validators
w  
Qiang Xue committed
362 363 364
	 */
	public function createValidators()
	{
w  
Qiang Xue committed
365 366
		$validators = new Vector;
		foreach ($this->rules() as $rule) {
Qiang Xue committed
367
			if (isset($rule[0], $rule[1])) { // attributes, validator type
w  
Qiang Xue committed
368 369
				$validator = \yii\validators\Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2));
				$validators->add($validator);
Qiang Xue committed
370
			} else {
w  
Qiang Xue committed
371
				throw new Exception('Invalid validation rule: a rule must specify both attribute names and validator type.');
w  
Qiang Xue committed
372
			}
w  
Qiang Xue committed
373 374 375 376 377 378 379
		}
		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
380
	 * [[\yii\validators\RequiredValidator|required]] validation rule in the
w  
Qiang Xue committed
381
	 * current [[scenario]].
w  
Qiang Xue committed
382 383 384 385 386
	 * @param string $attribute attribute name
	 * @return boolean whether the attribute is required
	 */
	public function isAttributeRequired($attribute)
	{
w  
Qiang Xue committed
387 388
		foreach ($this->getActiveValidators($attribute) as $validator) {
			if ($validator instanceof \yii\validators\RequiredValidator) {
w  
Qiang Xue committed
389
				return true;
w  
Qiang Xue committed
390
			}
w  
Qiang Xue committed
391 392 393 394 395 396 397 398 399 400 401
		}
		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)
	{
w  
Qiang Xue committed
402 403 404 405 406 407 408
		$validators = $this->getActiveValidators();
		foreach ($validators as $validator) {
			if (!$validator->safe) {
				return false;
			}
		}
		return $validators !== array();
w  
Qiang Xue committed
409 410 411 412 413 414 415 416 417 418 419
	}

	/**
	 * 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
420
		$labels = $this->attributeLabels();
Alex committed
421
		return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
w  
Qiang Xue committed
422 423 424 425 426 427 428
	}

	/**
	 * 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
429
	public function hasErrors($attribute = null)
w  
Qiang Xue committed
430
	{
w  
Qiang Xue committed
431
		return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
w  
Qiang Xue committed
432 433 434 435 436 437
	}

	/**
	 * 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
438 439
	 * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
	 *
w  
Qiang Xue committed
440
	 * ~~~
w  
Qiang Xue committed
441
	 * array(
Qiang Xue committed
442 443 444 445 446 447 448
	 *	 'username' => array(
	 *		 'Username is required.',
	 *		 'Username must contain only word characters.',
	 *	 ),
	 *	 'email' => array(
	 *		 'Email address is invalid.',
	 *	 )
w  
Qiang Xue committed
449 450 451 452
	 * )
	 * ~~~
	 *
	 * @see getError
w  
Qiang Xue committed
453
	 */
w  
Qiang Xue committed
454
	public function getErrors($attribute = null)
w  
Qiang Xue committed
455
	{
w  
Qiang Xue committed
456
		if ($attribute === null) {
w  
Qiang Xue committed
457
			return $this->_errors === null ? array() : $this->_errors;
Qiang Xue committed
458
		} else {
w  
Qiang Xue committed
459
			return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
w  
Qiang Xue committed
460
		}
w  
Qiang Xue committed
461 462 463 464 465 466
	}

	/**
	 * 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
467
	 * @see getErrors
w  
Qiang Xue committed
468 469 470 471 472 473 474 475 476 477 478
	 */
	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
479
	public function addError($attribute, $error)
w  
Qiang Xue committed
480
	{
w  
Qiang Xue committed
481
		$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
482 483 484 485 486 487 488 489 490 491
	}

	/**
	 * 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
492 493 494
		foreach ($errors as $attribute => $error) {
			if (is_array($error)) {
				foreach ($error as $e) {
w  
Qiang Xue committed
495
					$this->_errors[$attribute][] = $e;
w  
Qiang Xue committed
496
				}
Qiang Xue committed
497
			} else {
w  
Qiang Xue committed
498
				$this->_errors[$attribute][] = $error;
w  
Qiang Xue committed
499
			}
w  
Qiang Xue committed
500 501 502 503 504 505 506
		}
	}

	/**
	 * 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
507
	public function clearErrors($attribute = null)
w  
Qiang Xue committed
508
	{
w  
Qiang Xue committed
509
		if ($attribute === null) {
w  
Qiang Xue committed
510
			$this->_errors = array();
Qiang Xue committed
511
		} else {
w  
Qiang Xue committed
512
			unset($this->_errors[$attribute]);
w  
Qiang Xue committed
513
		}
w  
Qiang Xue committed
514 515 516
	}

	/**
w  
Qiang Xue committed
517 518
	 * 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
519
	 * changing the first letter of each word to upper case.
w  
Qiang Xue committed
520
	 * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
w  
Qiang Xue committed
521 522 523 524 525
	 * @param string $name the column name
	 * @return string the attribute label
	 */
	public function generateAttributeLabel($name)
	{
w  
Qiang Xue committed
526
		return ucwords(trim(strtolower(str_replace(array('-', '_', '.'), ' ', preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
w  
Qiang Xue committed
527 528 529
	}

	/**
w  
Qiang Xue committed
530
	 * Returns attribute values.
w  
Qiang Xue committed
531
	 * @param array $names list of attributes whose value needs to be returned.
w  
Qiang Xue committed
532
	 * Defaults to null, meaning all attributes listed in [[attributeNames]] will be returned.
w  
Qiang Xue committed
533 534 535
	 * If it is an array, only the attributes in the array will be returned.
	 * @return array attribute values (name=>value).
	 */
w  
Qiang Xue committed
536
	public function getAttributes($names = null)
w  
Qiang Xue committed
537
	{
w  
Qiang Xue committed
538
		$values = array();
w  
Qiang Xue committed
539

w  
Qiang Xue committed
540 541 542 543 544 545
		if (is_array($names)) {
			foreach ($this->attributeNames() as $name) {
				if (in_array($name, $names, true)) {
					$values[$name] = $this->$name;
				}
			}
Qiang Xue committed
546
		} else {
w  
Qiang Xue committed
547 548 549 550 551 552
			foreach ($this->attributeNames() as $name) {
				$values[$name] = $this->$name;
			}
		}

		return $values;
w  
Qiang Xue committed
553 554 555 556
	}

	/**
	 * Sets the attribute values in a massive way.
w  
Qiang Xue committed
557
	 * @param array $values attribute values (name=>value) to be assigned to the model.
w  
Qiang Xue committed
558
	 * @param boolean $safeOnly whether the assignments should only be done to the safe attributes.
w  
Qiang Xue committed
559
	 * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
w  
Qiang Xue committed
560 561 562
	 * @see getSafeAttributeNames
	 * @see attributeNames
	 */
w  
Qiang Xue committed
563
	public function setAttributes($values, $safeOnly = true)
w  
Qiang Xue committed
564
	{
w  
Qiang Xue committed
565 566 567 568 569
		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
570
				} elseif ($safeOnly) {
w  
Qiang Xue committed
571 572 573
					$this->onUnsafeAttribute($name, $value);
				}
			}
w  
Qiang Xue committed
574 575 576 577 578 579 580 581 582 583
		}
	}

	/**
	 * 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
584
	public function onUnsafeAttribute($name, $value)
w  
Qiang Xue committed
585
	{
w  
Qiang Xue committed
586
		if (YII_DEBUG) {
Qiang Xue committed
587
			\Yii::warning("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.");
w  
Qiang Xue committed
588
		}
w  
Qiang Xue committed
589 590 591 592 593 594 595 596
	}

	/**
	 * 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
597
	 * A validation rule will be performed when calling [[validate]]
w  
Qiang Xue committed
598 599 600
	 * 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
601 602 603
	 * 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
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
	 *
	 * @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
619
		$this->_scenario = $value;
w  
Qiang Xue committed
620 621 622 623
	}

	/**
	 * Returns the attribute names that are safe to be massively assigned.
w  
Qiang Xue committed
624
	 * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
w  
Qiang Xue committed
625 626 627 628
	 * @return array safe attribute names
	 */
	public function getSafeAttributeNames()
	{
w  
Qiang Xue committed
629 630
		$attributes = array();
		$unsafe = array();
w  
Qiang Xue committed
631
		foreach ($this->getActiveValidators() as $validator) {
w  
Qiang Xue committed
632 633
			if (!$validator->safe) {
				foreach ($validator->attributes as $name) {
w  
Qiang Xue committed
634
					$unsafe[] = $name;
w  
Qiang Xue committed
635
				}
Qiang Xue committed
636
			} else {
w  
Qiang Xue committed
637
				foreach ($validator->attributes as $name) {
w  
Qiang Xue committed
638
					$attributes[$name] = true;
w  
Qiang Xue committed
639
				}
w  
Qiang Xue committed
640 641 642
			}
		}

w  
Qiang Xue committed
643
		foreach ($unsafe as $name) {
w  
Qiang Xue committed
644
			unset($attributes[$name]);
w  
Qiang Xue committed
645
		}
w  
Qiang Xue committed
646 647 648 649 650 651 652 653 654 655
		return array_keys($attributes);
	}

	/**
	 * Returns an iterator for traversing the attributes in the model.
	 * This method is required by the interface IteratorAggregate.
	 * @return CMapIterator an iterator for traversing the items in the list.
	 */
	public function getIterator()
	{
w  
Qiang Xue committed
656 657
		$attributes = $this->getAttributes();
		return new DictionaryIterator($attributes);
w  
Qiang Xue committed
658 659 660 661
	}

	/**
	 * Returns whether there is an 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 `isset($model[$offset])`.
w  
Qiang Xue committed
664 665 666 667 668
	 * @param mixed $offset the offset to check on
	 * @return boolean
	 */
	public function offsetExists($offset)
	{
w  
Qiang Xue committed
669
		return property_exists($this, $offset) && $this->$offset !== null;
w  
Qiang Xue committed
670 671 672 673
	}

	/**
	 * Returns the element at the specified offset.
w  
Qiang Xue committed
674 675
	 * 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
676
	 * @param mixed $offset the offset to retrieve element.
w  
Qiang Xue committed
677 678 679 680 681 682 683 684 685
	 * @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
686 687
	 * 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
688 689 690
	 * @param integer $offset the offset to set element
	 * @param mixed $item the element value
	 */
w  
Qiang Xue committed
691
	public function offsetSet($offset, $item)
w  
Qiang Xue committed
692
	{
w  
Qiang Xue committed
693
		$this->$offset = $item;
w  
Qiang Xue committed
694 695 696 697
	}

	/**
	 * Unsets the element at the specified offset.
w  
Qiang Xue committed
698 699
	 * 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
700 701 702 703 704 705 706
	 * @param mixed $offset the offset to unset element
	 */
	public function offsetUnset($offset)
	{
		unset($this->$offset);
	}
}