Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

1010 lines
37KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use Yii;
  9. use ArrayAccess;
  10. use ArrayObject;
  11. use ArrayIterator;
  12. use ReflectionClass;
  13. use IteratorAggregate;
  14. use yii\helpers\Inflector;
  15. use yii\validators\RequiredValidator;
  16. use yii\validators\Validator;
  17. /**
  18. * Model is the base class for data models.
  19. *
  20. * Model implements the following commonly used features:
  21. *
  22. * - attribute declaration: by default, every public class member is considered as
  23. * a model attribute
  24. * - attribute labels: each attribute may be associated with a label for display purpose
  25. * - massive attribute assignment
  26. * - scenario-based validation
  27. *
  28. * Model also raises the following events when performing data validation:
  29. *
  30. * - [[EVENT_BEFORE_VALIDATE]]: an event raised at the beginning of [[validate()]]
  31. * - [[EVENT_AFTER_VALIDATE]]: an event raised at the end of [[validate()]]
  32. *
  33. * You may directly use Model to store model data, or extend it with customization.
  34. *
  35. * @property \yii\validators\Validator[] $activeValidators The validators applicable to the current
  36. * [[scenario]]. This property is read-only.
  37. * @property array $attributes Attribute values (name => value).
  38. * @property array $errors An array of errors for all attributes. Empty array is returned if no error. The
  39. * result is a two-dimensional array. See [[getErrors()]] for detailed description. This property is read-only.
  40. * @property array $firstErrors The first errors. The array keys are the attribute names, and the array values
  41. * are the corresponding error messages. An empty array will be returned if there is no error. This property is
  42. * read-only.
  43. * @property ArrayIterator $iterator An iterator for traversing the items in the list. This property is
  44. * read-only.
  45. * @property string $scenario The scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
  46. * @property ArrayObject|\yii\validators\Validator[] $validators All the validators declared in the model.
  47. * This property is read-only.
  48. *
  49. * @author Qiang Xue <qiang.xue@gmail.com>
  50. * @since 2.0
  51. */
  52. class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayable
  53. {
  54. use ArrayableTrait;
  55. /**
  56. * The name of the default scenario.
  57. */
  58. const SCENARIO_DEFAULT = 'default';
  59. /**
  60. * @event ModelEvent an event raised at the beginning of [[validate()]]. You may set
  61. * [[ModelEvent::isValid]] to be false to stop the validation.
  62. */
  63. const EVENT_BEFORE_VALIDATE = 'beforeValidate';
  64. /**
  65. * @event Event an event raised at the end of [[validate()]]
  66. */
  67. const EVENT_AFTER_VALIDATE = 'afterValidate';
  68. /**
  69. * @var array validation errors (attribute name => array of errors)
  70. */
  71. private $_errors;
  72. /**
  73. * @var ArrayObject list of validators
  74. */
  75. private $_validators;
  76. /**
  77. * @var string current scenario
  78. */
  79. private $_scenario = self::SCENARIO_DEFAULT;
  80. /**
  81. * Returns the validation rules for attributes.
  82. *
  83. * Validation rules are used by [[validate()]] to check if attribute values are valid.
  84. * Child classes may override this method to declare different validation rules.
  85. *
  86. * Each rule is an array with the following structure:
  87. *
  88. * ```php
  89. * [
  90. * ['attribute1', 'attribute2'],
  91. * 'validator type',
  92. * 'on' => ['scenario1', 'scenario2'],
  93. * //...other parameters...
  94. * ]
  95. * ```
  96. *
  97. * where
  98. *
  99. * - attribute list: required, specifies the attributes array to be validated, for single attribute you can pass a string;
  100. * - validator type: required, specifies the validator to be used. It can be a built-in validator name,
  101. * a method name of the model class, an anonymous function, or a validator class name.
  102. * - on: optional, specifies the [[scenario|scenarios]] array in which the validation
  103. * rule can be applied. If this option is not set, the rule will apply to all scenarios.
  104. * - additional name-value pairs can be specified to initialize the corresponding validator properties.
  105. * Please refer to individual validator class API for possible properties.
  106. *
  107. * A validator can be either an object of a class extending [[Validator]], or a model class method
  108. * (called *inline validator*) that has the following signature:
  109. *
  110. * ```php
  111. * // $params refers to validation parameters given in the rule
  112. * function validatorName($attribute, $params)
  113. * ```
  114. *
  115. * In the above `$attribute` refers to the attribute currently being validated while `$params` contains an array of
  116. * validator configuration options such as `max` in case of `string` validator. The value of the attribute currently being validated
  117. * can be accessed as `$this->$attribute`. Note the `$` before `attribute`; this is taking the value of the variable
  118. * `$attribute` and using it as the name of the property to access.
  119. *
  120. * Yii also provides a set of [[Validator::builtInValidators|built-in validators]].
  121. * Each one has an alias name which can be used when specifying a validation rule.
  122. *
  123. * Below are some examples:
  124. *
  125. * ```php
  126. * [
  127. * // built-in "required" validator
  128. * [['username', 'password'], 'required'],
  129. * // built-in "string" validator customized with "min" and "max" properties
  130. * ['username', 'string', 'min' => 3, 'max' => 12],
  131. * // built-in "compare" validator that is used in "register" scenario only
  132. * ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
  133. * // an inline validator defined via the "authenticate()" method in the model class
  134. * ['password', 'authenticate', 'on' => 'login'],
  135. * // a validator of class "DateRangeValidator"
  136. * ['dateRange', 'DateRangeValidator'],
  137. * ];
  138. * ```
  139. *
  140. * Note, in order to inherit rules defined in the parent class, a child class needs to
  141. * merge the parent rules with child rules using functions such as `array_merge()`.
  142. *
  143. * @return array validation rules
  144. * @see scenarios()
  145. */
  146. public function rules()
  147. {
  148. return [];
  149. }
  150. /**
  151. * Returns a list of scenarios and the corresponding active attributes.
  152. * An active attribute is one that is subject to validation in the current scenario.
  153. * The returned array should be in the following format:
  154. *
  155. * ```php
  156. * [
  157. * 'scenario1' => ['attribute11', 'attribute12', ...],
  158. * 'scenario2' => ['attribute21', 'attribute22', ...],
  159. * ...
  160. * ]
  161. * ```
  162. *
  163. * By default, an active attribute is considered safe and can be massively assigned.
  164. * If an attribute should NOT be massively assigned (thus considered unsafe),
  165. * please prefix the attribute with an exclamation character (e.g. `'!rank'`).
  166. *
  167. * The default implementation of this method will return all scenarios found in the [[rules()]]
  168. * declaration. A special scenario named [[SCENARIO_DEFAULT]] will contain all attributes
  169. * found in the [[rules()]]. Each scenario will be associated with the attributes that
  170. * are being validated by the validation rules that apply to the scenario.
  171. *
  172. * @return array a list of scenarios and the corresponding active attributes.
  173. */
  174. public function scenarios()
  175. {
  176. $scenarios = [self::SCENARIO_DEFAULT => []];
  177. foreach ($this->getValidators() as $validator) {
  178. foreach ($validator->on as $scenario) {
  179. $scenarios[$scenario] = [];
  180. }
  181. foreach ($validator->except as $scenario) {
  182. $scenarios[$scenario] = [];
  183. }
  184. }
  185. $names = array_keys($scenarios);
  186. foreach ($this->getValidators() as $validator) {
  187. if (empty($validator->on) && empty($validator->except)) {
  188. foreach ($names as $name) {
  189. foreach ($validator->attributes as $attribute) {
  190. $scenarios[$name][$attribute] = true;
  191. }
  192. }
  193. } elseif (empty($validator->on)) {
  194. foreach ($names as $name) {
  195. if (!in_array($name, $validator->except, true)) {
  196. foreach ($validator->attributes as $attribute) {
  197. $scenarios[$name][$attribute] = true;
  198. }
  199. }
  200. }
  201. } else {
  202. foreach ($validator->on as $name) {
  203. foreach ($validator->attributes as $attribute) {
  204. $scenarios[$name][$attribute] = true;
  205. }
  206. }
  207. }
  208. }
  209. foreach ($scenarios as $scenario => $attributes) {
  210. if (!empty($attributes)) {
  211. $scenarios[$scenario] = array_keys($attributes);
  212. }
  213. }
  214. return $scenarios;
  215. }
  216. /**
  217. * Returns the form name that this model class should use.
  218. *
  219. * The form name is mainly used by [[\yii\widgets\ActiveForm]] to determine how to name
  220. * the input fields for the attributes in a model. If the form name is "A" and an attribute
  221. * name is "b", then the corresponding input name would be "A[b]". If the form name is
  222. * an empty string, then the input name would be "b".
  223. *
  224. * The purpose of the above naming schema is that for forms which contain multiple different models,
  225. * the attributes of each model are grouped in sub-arrays of the POST-data and it is easier to
  226. * differentiate between them.
  227. *
  228. * By default, this method returns the model class name (without the namespace part)
  229. * as the form name. You may override it when the model is used in different forms.
  230. *
  231. * @return string the form name of this model class.
  232. * @see load()
  233. */
  234. public function formName()
  235. {
  236. $reflector = new ReflectionClass($this);
  237. return $reflector->getShortName();
  238. }
  239. /**
  240. * Returns the list of attribute names.
  241. * By default, this method returns all public non-static properties of the class.
  242. * You may override this method to change the default behavior.
  243. * @return array list of attribute names.
  244. */
  245. public function attributes()
  246. {
  247. $class = new ReflectionClass($this);
  248. $names = [];
  249. foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
  250. if (!$property->isStatic()) {
  251. $names[] = $property->getName();
  252. }
  253. }
  254. return $names;
  255. }
  256. /**
  257. * Returns the attribute labels.
  258. *
  259. * Attribute labels are mainly used for display purpose. For example, given an attribute
  260. * `firstName`, we can declare a label `First Name` which is more user-friendly and can
  261. * be displayed to end users.
  262. *
  263. * By default an attribute label is generated using [[generateAttributeLabel()]].
  264. * This method allows you to explicitly specify attribute labels.
  265. *
  266. * Note, in order to inherit labels defined in the parent class, a child class needs to
  267. * merge the parent labels with child labels using functions such as `array_merge()`.
  268. *
  269. * @return array attribute labels (name => label)
  270. * @see generateAttributeLabel()
  271. */
  272. public function attributeLabels()
  273. {
  274. return [];
  275. }
  276. /**
  277. * Returns the attribute hints.
  278. *
  279. * Attribute hints are mainly used for display purpose. For example, given an attribute
  280. * `isPublic`, we can declare a hint `Whether the post should be visible for not logged in users`,
  281. * which provides user-friendly description of the attribute meaning and can be displayed to end users.
  282. *
  283. * Unlike label hint will not be generated, if its explicit declaration is omitted.
  284. *
  285. * Note, in order to inherit hints defined in the parent class, a child class needs to
  286. * merge the parent hints with child hints using functions such as `array_merge()`.
  287. *
  288. * @return array attribute hints (name => hint)
  289. * @since 2.0.4
  290. */
  291. public function attributeHints()
  292. {
  293. return [];
  294. }
  295. /**
  296. * Performs the data validation.
  297. *
  298. * This method executes the validation rules applicable to the current [[scenario]].
  299. * The following criteria are used to determine whether a rule is currently applicable:
  300. *
  301. * - the rule must be associated with the attributes relevant to the current scenario;
  302. * - the rules must be effective for the current scenario.
  303. *
  304. * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
  305. * after the actual validation, respectively. If [[beforeValidate()]] returns false,
  306. * the validation will be cancelled and [[afterValidate()]] will not be called.
  307. *
  308. * Errors found during the validation can be retrieved via [[getErrors()]],
  309. * [[getFirstErrors()]] and [[getFirstError()]].
  310. *
  311. * @param array $attributeNames list of attribute names that should be validated.
  312. * If this parameter is empty, it means any attribute listed in the applicable
  313. * validation rules should be validated.
  314. * @param boolean $clearErrors whether to call [[clearErrors()]] before performing validation
  315. * @return boolean whether the validation is successful without any error.
  316. * @throws InvalidParamException if the current scenario is unknown.
  317. */
  318. public function validate($attributeNames = null, $clearErrors = true)
  319. {
  320. if ($clearErrors) {
  321. $this->clearErrors();
  322. }
  323. if (!$this->beforeValidate()) {
  324. return false;
  325. }
  326. $scenarios = $this->scenarios();
  327. $scenario = $this->getScenario();
  328. if (!isset($scenarios[$scenario])) {
  329. throw new InvalidParamException("Unknown scenario: $scenario");
  330. }
  331. if ($attributeNames === null) {
  332. $attributeNames = $this->activeAttributes();
  333. }
  334. foreach ($this->getActiveValidators() as $validator) {
  335. $validator->validateAttributes($this, $attributeNames);
  336. }
  337. $this->afterValidate();
  338. return !$this->hasErrors();
  339. }
  340. /**
  341. * This method is invoked before validation starts.
  342. * The default implementation raises a `beforeValidate` event.
  343. * You may override this method to do preliminary checks before validation.
  344. * Make sure the parent implementation is invoked so that the event can be raised.
  345. * @return boolean whether the validation should be executed. Defaults to true.
  346. * If false is returned, the validation will stop and the model is considered invalid.
  347. */
  348. public function beforeValidate()
  349. {
  350. $event = new ModelEvent;
  351. $this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
  352. return $event->isValid;
  353. }
  354. /**
  355. * This method is invoked after validation ends.
  356. * The default implementation raises an `afterValidate` event.
  357. * You may override this method to do postprocessing after validation.
  358. * Make sure the parent implementation is invoked so that the event can be raised.
  359. */
  360. public function afterValidate()
  361. {
  362. $this->trigger(self::EVENT_AFTER_VALIDATE);
  363. }
  364. /**
  365. * Returns all the validators declared in [[rules()]].
  366. *
  367. * This method differs from [[getActiveValidators()]] in that the latter
  368. * only returns the validators applicable to the current [[scenario]].
  369. *
  370. * Because this method returns an ArrayObject object, you may
  371. * manipulate it by inserting or removing validators (useful in model behaviors).
  372. * For example,
  373. *
  374. * ```php
  375. * $model->validators[] = $newValidator;
  376. * ```
  377. *
  378. * @return ArrayObject|\yii\validators\Validator[] all the validators declared in the model.
  379. */
  380. public function getValidators()
  381. {
  382. if ($this->_validators === null) {
  383. $this->_validators = $this->createValidators();
  384. }
  385. return $this->_validators;
  386. }
  387. /**
  388. * Returns the validators applicable to the current [[scenario]].
  389. * @param string $attribute the name of the attribute whose applicable validators should be returned.
  390. * If this is null, the validators for ALL attributes in the model will be returned.
  391. * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
  392. */
  393. public function getActiveValidators($attribute = null)
  394. {
  395. $validators = [];
  396. $scenario = $this->getScenario();
  397. foreach ($this->getValidators() as $validator) {
  398. if ($validator->isActive($scenario) && ($attribute === null || in_array($attribute, $validator->attributes, true))) {
  399. $validators[] = $validator;
  400. }
  401. }
  402. return $validators;
  403. }
  404. /**
  405. * Creates validator objects based on the validation rules specified in [[rules()]].
  406. * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
  407. * @return ArrayObject validators
  408. * @throws InvalidConfigException if any validation rule configuration is invalid
  409. */
  410. public function createValidators()
  411. {
  412. $validators = new ArrayObject;
  413. foreach ($this->rules() as $rule) {
  414. if ($rule instanceof Validator) {
  415. $validators->append($rule);
  416. } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
  417. $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2));
  418. $validators->append($validator);
  419. } else {
  420. throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
  421. }
  422. }
  423. return $validators;
  424. }
  425. /**
  426. * Returns a value indicating whether the attribute is required.
  427. * This is determined by checking if the attribute is associated with a
  428. * [[\yii\validators\RequiredValidator|required]] validation rule in the
  429. * current [[scenario]].
  430. *
  431. * Note that when the validator has a conditional validation applied using
  432. * [[\yii\validators\RequiredValidator::$when|$when]] this method will return
  433. * `false` regardless of the `when` condition because it may be called be
  434. * before the model is loaded with data.
  435. *
  436. * @param string $attribute attribute name
  437. * @return boolean whether the attribute is required
  438. */
  439. public function isAttributeRequired($attribute)
  440. {
  441. foreach ($this->getActiveValidators($attribute) as $validator) {
  442. if ($validator instanceof RequiredValidator && $validator->when === null) {
  443. return true;
  444. }
  445. }
  446. return false;
  447. }
  448. /**
  449. * Returns a value indicating whether the attribute is safe for massive assignments.
  450. * @param string $attribute attribute name
  451. * @return boolean whether the attribute is safe for massive assignments
  452. * @see safeAttributes()
  453. */
  454. public function isAttributeSafe($attribute)
  455. {
  456. return in_array($attribute, $this->safeAttributes(), true);
  457. }
  458. /**
  459. * Returns a value indicating whether the attribute is active in the current scenario.
  460. * @param string $attribute attribute name
  461. * @return boolean whether the attribute is active in the current scenario
  462. * @see activeAttributes()
  463. */
  464. public function isAttributeActive($attribute)
  465. {
  466. return in_array($attribute, $this->activeAttributes(), true);
  467. }
  468. /**
  469. * Returns the text label for the specified attribute.
  470. * @param string $attribute the attribute name
  471. * @return string the attribute label
  472. * @see generateAttributeLabel()
  473. * @see attributeLabels()
  474. */
  475. public function getAttributeLabel($attribute)
  476. {
  477. $labels = $this->attributeLabels();
  478. return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
  479. }
  480. /**
  481. * Returns the text hint for the specified attribute.
  482. * @param string $attribute the attribute name
  483. * @return string the attribute hint
  484. * @see attributeHints()
  485. * @since 2.0.4
  486. */
  487. public function getAttributeHint($attribute)
  488. {
  489. $hints = $this->attributeHints();
  490. return isset($hints[$attribute]) ? $hints[$attribute] : '';
  491. }
  492. /**
  493. * Returns a value indicating whether there is any validation error.
  494. * @param string|null $attribute attribute name. Use null to check all attributes.
  495. * @return boolean whether there is any error.
  496. */
  497. public function hasErrors($attribute = null)
  498. {
  499. return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
  500. }
  501. /**
  502. * Returns the errors for all attribute or a single attribute.
  503. * @param string $attribute attribute name. Use null to retrieve errors for all attributes.
  504. * @property array An array of errors for all attributes. Empty array is returned if no error.
  505. * The result is a two-dimensional array. See [[getErrors()]] for detailed description.
  506. * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
  507. * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
  508. *
  509. * ```php
  510. * [
  511. * 'username' => [
  512. * 'Username is required.',
  513. * 'Username must contain only word characters.',
  514. * ],
  515. * 'email' => [
  516. * 'Email address is invalid.',
  517. * ]
  518. * ]
  519. * ```
  520. *
  521. * @see getFirstErrors()
  522. * @see getFirstError()
  523. */
  524. public function getErrors($attribute = null)
  525. {
  526. if ($attribute === null) {
  527. return $this->_errors === null ? [] : $this->_errors;
  528. } else {
  529. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
  530. }
  531. }
  532. /**
  533. * Returns the first error of every attribute in the model.
  534. * @return array the first errors. The array keys are the attribute names, and the array
  535. * values are the corresponding error messages. An empty array will be returned if there is no error.
  536. * @see getErrors()
  537. * @see getFirstError()
  538. */
  539. public function getFirstErrors()
  540. {
  541. if (empty($this->_errors)) {
  542. return [];
  543. } else {
  544. $errors = [];
  545. foreach ($this->_errors as $name => $es) {
  546. if (!empty($es)) {
  547. $errors[$name] = reset($es);
  548. }
  549. }
  550. return $errors;
  551. }
  552. }
  553. /**
  554. * Returns the first error of the specified attribute.
  555. * @param string $attribute attribute name.
  556. * @return string the error message. Null is returned if no error.
  557. * @see getErrors()
  558. * @see getFirstErrors()
  559. */
  560. public function getFirstError($attribute)
  561. {
  562. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  563. }
  564. /**
  565. * Adds a new error to the specified attribute.
  566. * @param string $attribute attribute name
  567. * @param string $error new error message
  568. */
  569. public function addError($attribute, $error = '')
  570. {
  571. $this->_errors[$attribute][] = $error;
  572. }
  573. /**
  574. * Adds a list of errors.
  575. * @param array $items a list of errors. The array keys must be attribute names.
  576. * The array values should be error messages. If an attribute has multiple errors,
  577. * these errors must be given in terms of an array.
  578. * You may use the result of [[getErrors()]] as the value for this parameter.
  579. * @since 2.0.2
  580. */
  581. public function addErrors(array $items)
  582. {
  583. foreach ($items as $attribute => $errors) {
  584. if (is_array($errors)) {
  585. foreach ($errors as $error) {
  586. $this->addError($attribute, $error);
  587. }
  588. } else {
  589. $this->addError($attribute, $errors);
  590. }
  591. }
  592. }
  593. /**
  594. * Removes errors for all attributes or a single attribute.
  595. * @param string $attribute attribute name. Use null to remove errors for all attribute.
  596. */
  597. public function clearErrors($attribute = null)
  598. {
  599. if ($attribute === null) {
  600. $this->_errors = [];
  601. } else {
  602. unset($this->_errors[$attribute]);
  603. }
  604. }
  605. /**
  606. * Generates a user friendly attribute label based on the give attribute name.
  607. * This is done by replacing underscores, dashes and dots with blanks and
  608. * changing the first letter of each word to upper case.
  609. * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
  610. * @param string $name the column name
  611. * @return string the attribute label
  612. */
  613. public function generateAttributeLabel($name)
  614. {
  615. return Inflector::camel2words($name, true);
  616. }
  617. /**
  618. * Returns attribute values.
  619. * @param array $names list of attributes whose value needs to be returned.
  620. * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
  621. * If it is an array, only the attributes in the array will be returned.
  622. * @param array $except list of attributes whose value should NOT be returned.
  623. * @return array attribute values (name => value).
  624. */
  625. public function getAttributes($names = null, $except = [])
  626. {
  627. $values = [];
  628. if ($names === null) {
  629. $names = $this->attributes();
  630. }
  631. foreach ($names as $name) {
  632. $values[$name] = $this->$name;
  633. }
  634. foreach ($except as $name) {
  635. unset($values[$name]);
  636. }
  637. return $values;
  638. }
  639. /**
  640. * Sets the attribute values in a massive way.
  641. * @param array $values attribute values (name => value) to be assigned to the model.
  642. * @param boolean $safeOnly whether the assignments should only be done to the safe attributes.
  643. * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
  644. * @see safeAttributes()
  645. * @see attributes()
  646. */
  647. public function setAttributes($values, $safeOnly = true)
  648. {
  649. if (is_array($values)) {
  650. $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
  651. foreach ($values as $name => $value) {
  652. if (isset($attributes[$name])) {
  653. $this->$name = $value;
  654. } elseif ($safeOnly) {
  655. $this->onUnsafeAttribute($name, $value);
  656. }
  657. }
  658. }
  659. }
  660. /**
  661. * This method is invoked when an unsafe attribute is being massively assigned.
  662. * The default implementation will log a warning message if YII_DEBUG is on.
  663. * It does nothing otherwise.
  664. * @param string $name the unsafe attribute name
  665. * @param mixed $value the attribute value
  666. */
  667. public function onUnsafeAttribute($name, $value)
  668. {
  669. if (YII_DEBUG) {
  670. Yii::trace("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __METHOD__);
  671. }
  672. }
  673. /**
  674. * Returns the scenario that this model is used in.
  675. *
  676. * Scenario affects how validation is performed and which attributes can
  677. * be massively assigned.
  678. *
  679. * @return string the scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
  680. */
  681. public function getScenario()
  682. {
  683. return $this->_scenario;
  684. }
  685. /**
  686. * Sets the scenario for the model.
  687. * Note that this method does not check if the scenario exists or not.
  688. * The method [[validate()]] will perform this check.
  689. * @param string $value the scenario that this model is in.
  690. */
  691. public function setScenario($value)
  692. {
  693. $this->_scenario = $value;
  694. }
  695. /**
  696. * Returns the attribute names that are safe to be massively assigned in the current scenario.
  697. * @return string[] safe attribute names
  698. */
  699. public function safeAttributes()
  700. {
  701. $scenario = $this->getScenario();
  702. $scenarios = $this->scenarios();
  703. if (!isset($scenarios[$scenario])) {
  704. return [];
  705. }
  706. $attributes = [];
  707. foreach ($scenarios[$scenario] as $attribute) {
  708. if ($attribute[0] !== '!' && !in_array('!' . $attribute, $scenarios[$scenario])) {
  709. $attributes[] = $attribute;
  710. }
  711. }
  712. return $attributes;
  713. }
  714. /**
  715. * Returns the attribute names that are subject to validation in the current scenario.
  716. * @return string[] safe attribute names
  717. */
  718. public function activeAttributes()
  719. {
  720. $scenario = $this->getScenario();
  721. $scenarios = $this->scenarios();
  722. if (!isset($scenarios[$scenario])) {
  723. return [];
  724. }
  725. $attributes = $scenarios[$scenario];
  726. foreach ($attributes as $i => $attribute) {
  727. if ($attribute[0] === '!') {
  728. $attributes[$i] = substr($attribute, 1);
  729. }
  730. }
  731. return $attributes;
  732. }
  733. /**
  734. * Populates the model with input data.
  735. *
  736. * This method provides a convenient shortcut for:
  737. *
  738. * ```php
  739. * if (isset($_POST['FormName'])) {
  740. * $model->attributes = $_POST['FormName'];
  741. * if ($model->save()) {
  742. * // handle success
  743. * }
  744. * }
  745. * ```
  746. *
  747. * which, with `load()` can be written as:
  748. *
  749. * ```php
  750. * if ($model->load($_POST) && $model->save()) {
  751. * // handle success
  752. * }
  753. * ```
  754. *
  755. * `load()` gets the `'FormName'` from the model's [[formName()]] method (which you may override), unless the
  756. * `$formName` parameter is given. If the form name is empty, `load()` populates the model with the whole of `$data`,
  757. * instead of `$data['FormName']`.
  758. *
  759. * Note, that the data being populated is subject to the safety check by [[setAttributes()]].
  760. *
  761. * @param array $data the data array to load, typically `$_POST` or `$_GET`.
  762. * @param string $formName the form name to use to load the data into the model.
  763. * If not set, [[formName()]] is used.
  764. * @return boolean whether `load()` found the expected form in `$data`.
  765. */
  766. public function load($data, $formName = null)
  767. {
  768. $scope = $formName === null ? $this->formName() : $formName;
  769. if ($scope === '' && !empty($data)) {
  770. $this->setAttributes($data);
  771. return true;
  772. } elseif (isset($data[$scope])) {
  773. $this->setAttributes($data[$scope]);
  774. return true;
  775. } else {
  776. return false;
  777. }
  778. }
  779. /**
  780. * Populates a set of models with the data from end user.
  781. * This method is mainly used to collect tabular data input.
  782. * The data to be loaded for each model is `$data[formName][index]`, where `formName`
  783. * refers to the value of [[formName()]], and `index` the index of the model in the `$models` array.
  784. * If [[formName()]] is empty, `$data[index]` will be used to populate each model.
  785. * The data being populated to each model is subject to the safety check by [[setAttributes()]].
  786. * @param array $models the models to be populated. Note that all models should have the same class.
  787. * @param array $data the data array. This is usually `$_POST` or `$_GET`, but can also be any valid array
  788. * supplied by end user.
  789. * @param string $formName the form name to be used for loading the data into the models.
  790. * If not set, it will use the [[formName()]] value of the first model in `$models`.
  791. * This parameter is available since version 2.0.1.
  792. * @return boolean whether at least one of the models is successfully populated.
  793. */
  794. public static function loadMultiple($models, $data, $formName = null)
  795. {
  796. if ($formName === null) {
  797. /* @var $first Model */
  798. $first = reset($models);
  799. if ($first === false) {
  800. return false;
  801. }
  802. $formName = $first->formName();
  803. }
  804. $success = false;
  805. foreach ($models as $i => $model) {
  806. /* @var $model Model */
  807. if ($formName == '') {
  808. if (!empty($data[$i])) {
  809. $model->load($data[$i], '');
  810. $success = true;
  811. }
  812. } elseif (!empty($data[$formName][$i])) {
  813. $model->load($data[$formName][$i], '');
  814. $success = true;
  815. }
  816. }
  817. return $success;
  818. }
  819. /**
  820. * Validates multiple models.
  821. * This method will validate every model. The models being validated may
  822. * be of the same or different types.
  823. * @param array $models the models to be validated
  824. * @param array $attributeNames list of attribute names that should be validated.
  825. * If this parameter is empty, it means any attribute listed in the applicable
  826. * validation rules should be validated.
  827. * @return boolean whether all models are valid. False will be returned if one
  828. * or multiple models have validation error.
  829. */
  830. public static function validateMultiple($models, $attributeNames = null)
  831. {
  832. $valid = true;
  833. /* @var $model Model */
  834. foreach ($models as $model) {
  835. $valid = $model->validate($attributeNames) && $valid;
  836. }
  837. return $valid;
  838. }
  839. /**
  840. * Returns the list of fields that should be returned by default by [[toArray()]] when no specific fields are specified.
  841. *
  842. * A field is a named element in the returned array by [[toArray()]].
  843. *
  844. * This method should return an array of field names or field definitions.
  845. * If the former, the field name will be treated as an object property name whose value will be used
  846. * as the field value. If the latter, the array key should be the field name while the array value should be
  847. * the corresponding field definition which can be either an object property name or a PHP callable
  848. * returning the corresponding field value. The signature of the callable should be:
  849. *
  850. * ```php
  851. * function ($model, $field) {
  852. * // return field value
  853. * }
  854. * ```
  855. *
  856. * For example, the following code declares four fields:
  857. *
  858. * - `email`: the field name is the same as the property name `email`;
  859. * - `firstName` and `lastName`: the field names are `firstName` and `lastName`, and their
  860. * values are obtained from the `first_name` and `last_name` properties;
  861. * - `fullName`: the field name is `fullName`. Its value is obtained by concatenating `first_name`
  862. * and `last_name`.
  863. *
  864. * ```php
  865. * return [
  866. * 'email',
  867. * 'firstName' => 'first_name',
  868. * 'lastName' => 'last_name',
  869. * 'fullName' => function ($model) {
  870. * return $model->first_name . ' ' . $model->last_name;
  871. * },
  872. * ];
  873. * ```
  874. *
  875. * In this method, you may also want to return different lists of fields based on some context
  876. * information. For example, depending on [[scenario]] or the privilege of the current application user,
  877. * you may return different sets of visible fields or filter out some fields.
  878. *
  879. * The default implementation of this method returns [[attributes()]] indexed by the same attribute names.
  880. *
  881. * @return array the list of field names or field definitions.
  882. * @see toArray()
  883. */
  884. public function fields()
  885. {
  886. $fields = $this->attributes();
  887. return array_combine($fields, $fields);
  888. }
  889. /**
  890. * Returns an iterator for traversing the attributes in the model.
  891. * This method is required by the interface [[\IteratorAggregate]].
  892. * @return ArrayIterator an iterator for traversing the items in the list.
  893. */
  894. public function getIterator()
  895. {
  896. $attributes = $this->getAttributes();
  897. return new ArrayIterator($attributes);
  898. }
  899. /**
  900. * Returns whether there is an element at the specified offset.
  901. * This method is required by the SPL interface [[\ArrayAccess]].
  902. * It is implicitly called when you use something like `isset($model[$offset])`.
  903. * @param mixed $offset the offset to check on.
  904. * @return boolean whether or not an offset exists.
  905. */
  906. public function offsetExists($offset)
  907. {
  908. return isset($this->$offset);
  909. }
  910. /**
  911. * Returns the element at the specified offset.
  912. * This method is required by the SPL interface [[\ArrayAccess]].
  913. * It is implicitly called when you use something like `$value = $model[$offset];`.
  914. * @param mixed $offset the offset to retrieve element.
  915. * @return mixed the element at the offset, null if no element is found at the offset
  916. */
  917. public function offsetGet($offset)
  918. {
  919. return $this->$offset;
  920. }
  921. /**
  922. * Sets the element at the specified offset.
  923. * This method is required by the SPL interface [[\ArrayAccess]].
  924. * It is implicitly called when you use something like `$model[$offset] = $item;`.
  925. * @param integer $offset the offset to set element
  926. * @param mixed $item the element value
  927. */
  928. public function offsetSet($offset, $item)
  929. {
  930. $this->$offset = $item;
  931. }
  932. /**
  933. * Sets the element value at the specified offset to null.
  934. * This method is required by the SPL interface [[\ArrayAccess]].
  935. * It is implicitly called when you use something like `unset($model[$offset])`.
  936. * @param mixed $offset the offset to unset element
  937. */
  938. public function offsetUnset($offset)
  939. {
  940. $this->$offset = null;
  941. }
  942. }