You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

952 lines
35KB

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