Model.php 38 KB

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