Model.php 39 KB

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