Model.php 40 KB

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