Model.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  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-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-read ArrayIterator $iterator An iterator for traversing the items in the list.
  47. * @property string $scenario The scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
  48. * @property-read ArrayObject|\yii\validators\Validator[] $validators All the validators declared in the
  49. * model.
  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|null $attributeNames attribute name or list of attribute names
  321. * that should be validated. If this parameter is empty, it means any attribute listed in
  322. * the applicable 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|null $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. $activeAttributes = $this->activeAttributes();
  406. if ($attribute !== null && !in_array($attribute, $activeAttributes, true)) {
  407. return [];
  408. }
  409. $scenario = $this->getScenario();
  410. $validators = [];
  411. foreach ($this->getValidators() as $validator) {
  412. if ($attribute === null) {
  413. $validatorAttributes = $validator->getValidationAttributes($activeAttributes);
  414. $attributeValid = !empty($validatorAttributes);
  415. } else {
  416. $attributeValid = in_array($attribute, $validator->getValidationAttributes($attribute), true);
  417. }
  418. if ($attributeValid && $validator->isActive($scenario)) {
  419. $validators[] = $validator;
  420. }
  421. }
  422. return $validators;
  423. }
  424. /**
  425. * Creates validator objects based on the validation rules specified in [[rules()]].
  426. * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
  427. * @return ArrayObject validators
  428. * @throws InvalidConfigException if any validation rule configuration is invalid
  429. */
  430. public function createValidators()
  431. {
  432. $validators = new ArrayObject();
  433. foreach ($this->rules() as $rule) {
  434. if ($rule instanceof Validator) {
  435. $validators->append($rule);
  436. } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
  437. $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2));
  438. $validators->append($validator);
  439. } else {
  440. throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
  441. }
  442. }
  443. return $validators;
  444. }
  445. /**
  446. * Returns a value indicating whether the attribute is required.
  447. * This is determined by checking if the attribute is associated with a
  448. * [[\yii\validators\RequiredValidator|required]] validation rule in the
  449. * current [[scenario]].
  450. *
  451. * Note that when the validator has a conditional validation applied using
  452. * [[\yii\validators\RequiredValidator::$when|$when]] this method will return
  453. * `false` regardless of the `when` condition because it may be called be
  454. * before the model is loaded with data.
  455. *
  456. * @param string $attribute attribute name
  457. * @return bool whether the attribute is required
  458. */
  459. public function isAttributeRequired($attribute)
  460. {
  461. foreach ($this->getActiveValidators($attribute) as $validator) {
  462. if ($validator instanceof RequiredValidator && $validator->when === null) {
  463. return true;
  464. }
  465. }
  466. return false;
  467. }
  468. /**
  469. * Returns a value indicating whether the attribute is safe for massive assignments.
  470. * @param string $attribute attribute name
  471. * @return bool whether the attribute is safe for massive assignments
  472. * @see safeAttributes()
  473. */
  474. public function isAttributeSafe($attribute)
  475. {
  476. return in_array($attribute, $this->safeAttributes(), true);
  477. }
  478. /**
  479. * Returns a value indicating whether the attribute is active in the current scenario.
  480. * @param string $attribute attribute name
  481. * @return bool whether the attribute is active in the current scenario
  482. * @see activeAttributes()
  483. */
  484. public function isAttributeActive($attribute)
  485. {
  486. return in_array($attribute, $this->activeAttributes(), true);
  487. }
  488. /**
  489. * Returns the text label for the specified attribute.
  490. * @param string $attribute the attribute name
  491. * @return string the attribute label
  492. * @see generateAttributeLabel()
  493. * @see attributeLabels()
  494. */
  495. public function getAttributeLabel($attribute)
  496. {
  497. $labels = $this->attributeLabels();
  498. return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
  499. }
  500. /**
  501. * Returns the text hint for the specified attribute.
  502. * @param string $attribute the attribute name
  503. * @return string the attribute hint
  504. * @see attributeHints()
  505. * @since 2.0.4
  506. */
  507. public function getAttributeHint($attribute)
  508. {
  509. $hints = $this->attributeHints();
  510. return isset($hints[$attribute]) ? $hints[$attribute] : '';
  511. }
  512. /**
  513. * Returns a value indicating whether there is any validation error.
  514. * @param string|null $attribute attribute name. Use null to check all attributes.
  515. * @return bool whether there is any error.
  516. */
  517. public function hasErrors($attribute = null)
  518. {
  519. return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
  520. }
  521. /**
  522. * Returns the errors for all attributes or a single attribute.
  523. * @param string|null $attribute attribute name. Use null to retrieve errors for all attributes.
  524. * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
  525. * See [[getErrors()]] for detailed description.
  526. * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
  527. *
  528. * ```php
  529. * [
  530. * 'username' => [
  531. * 'Username is required.',
  532. * 'Username must contain only word characters.',
  533. * ],
  534. * 'email' => [
  535. * 'Email address is invalid.',
  536. * ]
  537. * ]
  538. * ```
  539. *
  540. * @see getFirstErrors()
  541. * @see getFirstError()
  542. */
  543. public function getErrors($attribute = null)
  544. {
  545. if ($attribute === null) {
  546. return $this->_errors === null ? [] : $this->_errors;
  547. }
  548. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
  549. }
  550. /**
  551. * Returns the first error of every attribute in the model.
  552. * @return array the first errors. The array keys are the attribute names, and the array
  553. * values are the corresponding error messages. An empty array will be returned if there is no error.
  554. * @see getErrors()
  555. * @see getFirstError()
  556. */
  557. public function getFirstErrors()
  558. {
  559. if (empty($this->_errors)) {
  560. return [];
  561. }
  562. $errors = [];
  563. foreach ($this->_errors as $name => $es) {
  564. if (!empty($es)) {
  565. $errors[$name] = reset($es);
  566. }
  567. }
  568. return $errors;
  569. }
  570. /**
  571. * Returns the first error of the specified attribute.
  572. * @param string $attribute attribute name.
  573. * @return string|null the error message. Null is returned if no error.
  574. * @see getErrors()
  575. * @see getFirstErrors()
  576. */
  577. public function getFirstError($attribute)
  578. {
  579. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  580. }
  581. /**
  582. * Returns the errors for all attributes as a one-dimensional array.
  583. * @param bool $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
  584. * only the first error message for each attribute will be shown.
  585. * @return array errors for all attributes as a one-dimensional array. Empty array is returned if no error.
  586. * @see getErrors()
  587. * @see getFirstErrors()
  588. * @since 2.0.14
  589. */
  590. public function getErrorSummary($showAllErrors)
  591. {
  592. $lines = [];
  593. $errors = $showAllErrors ? $this->getErrors() : $this->getFirstErrors();
  594. foreach ($errors as $es) {
  595. $lines = array_merge($lines, (array)$es);
  596. }
  597. return $lines;
  598. }
  599. /**
  600. * Adds a new error to the specified attribute.
  601. * @param string $attribute attribute name
  602. * @param string $error new error message
  603. */
  604. public function addError($attribute, $error = '')
  605. {
  606. $this->_errors[$attribute][] = $error;
  607. }
  608. /**
  609. * Adds a list of errors.
  610. * @param array $items a list of errors. The array keys must be attribute names.
  611. * The array values should be error messages. If an attribute has multiple errors,
  612. * these errors must be given in terms of an array.
  613. * You may use the result of [[getErrors()]] as the value for this parameter.
  614. * @since 2.0.2
  615. */
  616. public function addErrors(array $items)
  617. {
  618. foreach ($items as $attribute => $errors) {
  619. if (is_array($errors)) {
  620. foreach ($errors as $error) {
  621. $this->addError($attribute, $error);
  622. }
  623. } else {
  624. $this->addError($attribute, $errors);
  625. }
  626. }
  627. }
  628. /**
  629. * Removes errors for all attributes or a single attribute.
  630. * @param string|null $attribute attribute name. Use null to remove errors for all attributes.
  631. */
  632. public function clearErrors($attribute = null)
  633. {
  634. if ($attribute === null) {
  635. $this->_errors = [];
  636. } else {
  637. unset($this->_errors[$attribute]);
  638. }
  639. }
  640. /**
  641. * Generates a user friendly attribute label based on the give attribute name.
  642. * This is done by replacing underscores, dashes and dots with blanks and
  643. * changing the first letter of each word to upper case.
  644. * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
  645. * @param string $name the column name
  646. * @return string the attribute label
  647. */
  648. public function generateAttributeLabel($name)
  649. {
  650. return Inflector::camel2words($name, true);
  651. }
  652. /**
  653. * Returns attribute values.
  654. * @param array|null $names list of attributes whose value needs to be returned.
  655. * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
  656. * If it is an array, only the attributes in the array will be returned.
  657. * @param array $except list of attributes whose value should NOT be returned.
  658. * @return array attribute values (name => value).
  659. */
  660. public function getAttributes($names = null, $except = [])
  661. {
  662. $values = [];
  663. if ($names === null) {
  664. $names = $this->attributes();
  665. }
  666. foreach ($names as $name) {
  667. $values[$name] = $this->$name;
  668. }
  669. foreach ($except as $name) {
  670. unset($values[$name]);
  671. }
  672. return $values;
  673. }
  674. /**
  675. * Sets the attribute values in a massive way.
  676. * @param array $values attribute values (name => value) to be assigned to the model.
  677. * @param bool $safeOnly whether the assignments should only be done to the safe attributes.
  678. * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
  679. * @see safeAttributes()
  680. * @see attributes()
  681. */
  682. public function setAttributes($values, $safeOnly = true)
  683. {
  684. if (is_array($values)) {
  685. $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
  686. foreach ($values as $name => $value) {
  687. if (isset($attributes[$name])) {
  688. $this->$name = $value;
  689. } elseif ($safeOnly) {
  690. $this->onUnsafeAttribute($name, $value);
  691. }
  692. }
  693. }
  694. }
  695. /**
  696. * This method is invoked when an unsafe attribute is being massively assigned.
  697. * The default implementation will log a warning message if YII_DEBUG is on.
  698. * It does nothing otherwise.
  699. * @param string $name the unsafe attribute name
  700. * @param mixed $value the attribute value
  701. */
  702. public function onUnsafeAttribute($name, $value)
  703. {
  704. if (YII_DEBUG) {
  705. Yii::debug("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __METHOD__);
  706. }
  707. }
  708. /**
  709. * Returns the scenario that this model is used in.
  710. *
  711. * Scenario affects how validation is performed and which attributes can
  712. * be massively assigned.
  713. *
  714. * @return string the scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
  715. */
  716. public function getScenario()
  717. {
  718. return $this->_scenario;
  719. }
  720. /**
  721. * Sets the scenario for the model.
  722. * Note that this method does not check if the scenario exists or not.
  723. * The method [[validate()]] will perform this check.
  724. * @param string $value the scenario that this model is in.
  725. */
  726. public function setScenario($value)
  727. {
  728. $this->_scenario = $value;
  729. }
  730. /**
  731. * Returns the attribute names that are safe to be massively assigned in the current scenario.
  732. * @return string[] safe attribute names
  733. */
  734. public function safeAttributes()
  735. {
  736. $scenario = $this->getScenario();
  737. $scenarios = $this->scenarios();
  738. if (!isset($scenarios[$scenario])) {
  739. return [];
  740. }
  741. $attributes = [];
  742. foreach ($scenarios[$scenario] as $attribute) {
  743. if (strncmp($attribute, '!', 1) !== 0 && !in_array('!' . $attribute, $scenarios[$scenario])) {
  744. $attributes[] = $attribute;
  745. }
  746. }
  747. return $attributes;
  748. }
  749. /**
  750. * Returns the attribute names that are subject to validation in the current scenario.
  751. * @return string[] safe attribute names
  752. */
  753. public function activeAttributes()
  754. {
  755. $scenario = $this->getScenario();
  756. $scenarios = $this->scenarios();
  757. if (!isset($scenarios[$scenario])) {
  758. return [];
  759. }
  760. $attributes = array_keys(array_flip($scenarios[$scenario]));
  761. foreach ($attributes as $i => $attribute) {
  762. if (strncmp($attribute, '!', 1) === 0) {
  763. $attributes[$i] = substr($attribute, 1);
  764. }
  765. }
  766. return $attributes;
  767. }
  768. /**
  769. * Populates the model with input data.
  770. *
  771. * This method provides a convenient shortcut for:
  772. *
  773. * ```php
  774. * if (isset($_POST['FormName'])) {
  775. * $model->attributes = $_POST['FormName'];
  776. * if ($model->save()) {
  777. * // handle success
  778. * }
  779. * }
  780. * ```
  781. *
  782. * which, with `load()` can be written as:
  783. *
  784. * ```php
  785. * if ($model->load($_POST) && $model->save()) {
  786. * // handle success
  787. * }
  788. * ```
  789. *
  790. * `load()` gets the `'FormName'` from the model's [[formName()]] method (which you may override), unless the
  791. * `$formName` parameter is given. If the form name is empty, `load()` populates the model with the whole of `$data`,
  792. * instead of `$data['FormName']`.
  793. *
  794. * Note, that the data being populated is subject to the safety check by [[setAttributes()]].
  795. *
  796. * @param array $data the data array to load, typically `$_POST` or `$_GET`.
  797. * @param string|null $formName the form name to use to load the data into the model, empty string when form not use.
  798. * If not set, [[formName()]] is used.
  799. * @return bool whether `load()` found the expected form in `$data`.
  800. */
  801. public function load($data, $formName = null)
  802. {
  803. $scope = $formName === null ? $this->formName() : $formName;
  804. if ($scope === '' && !empty($data)) {
  805. $this->setAttributes($data);
  806. return true;
  807. } elseif (isset($data[$scope])) {
  808. $this->setAttributes($data[$scope]);
  809. return true;
  810. }
  811. return false;
  812. }
  813. /**
  814. * Populates a set of models with the data from end user.
  815. * This method is mainly used to collect tabular data input.
  816. * The data to be loaded for each model is `$data[formName][index]`, where `formName`
  817. * refers to the value of [[formName()]], and `index` the index of the model in the `$models` array.
  818. * If [[formName()]] is empty, `$data[index]` will be used to populate each model.
  819. * The data being populated to each model is subject to the safety check by [[setAttributes()]].
  820. * @param array $models the models to be populated. Note that all models should have the same class.
  821. * @param array $data the data array. This is usually `$_POST` or `$_GET`, but can also be any valid array
  822. * supplied by end user.
  823. * @param string|null $formName the form name to be used for loading the data into the models.
  824. * If not set, it will use the [[formName()]] value of the first model in `$models`.
  825. * This parameter is available since version 2.0.1.
  826. * @return bool whether at least one of the models is successfully populated.
  827. */
  828. public static function loadMultiple($models, $data, $formName = null)
  829. {
  830. if ($formName === null) {
  831. /* @var $first Model|false */
  832. $first = reset($models);
  833. if ($first === false) {
  834. return false;
  835. }
  836. $formName = $first->formName();
  837. }
  838. $success = false;
  839. foreach ($models as $i => $model) {
  840. /* @var $model Model */
  841. if ($formName == '') {
  842. if (!empty($data[$i]) && $model->load($data[$i], '')) {
  843. $success = true;
  844. }
  845. } elseif (!empty($data[$formName][$i]) && $model->load($data[$formName][$i], '')) {
  846. $success = true;
  847. }
  848. }
  849. return $success;
  850. }
  851. /**
  852. * Validates multiple models.
  853. * This method will validate every model. The models being validated may
  854. * be of the same or different types.
  855. * @param array $models the models to be validated
  856. * @param array|null $attributeNames list of attribute names that should be validated.
  857. * If this parameter is empty, it means any attribute listed in the applicable
  858. * validation rules should be validated.
  859. * @return bool whether all models are valid. False will be returned if one
  860. * or multiple models have validation error.
  861. */
  862. public static function validateMultiple($models, $attributeNames = null)
  863. {
  864. $valid = true;
  865. /* @var $model Model */
  866. foreach ($models as $model) {
  867. $valid = $model->validate($attributeNames) && $valid;
  868. }
  869. return $valid;
  870. }
  871. /**
  872. * Returns the list of fields that should be returned by default by [[toArray()]] when no specific fields are specified.
  873. *
  874. * A field is a named element in the returned array by [[toArray()]].
  875. *
  876. * This method should return an array of field names or field definitions.
  877. * If the former, the field name will be treated as an object property name whose value will be used
  878. * as the field value. If the latter, the array key should be the field name while the array value should be
  879. * the corresponding field definition which can be either an object property name or a PHP callable
  880. * returning the corresponding field value. The signature of the callable should be:
  881. *
  882. * ```php
  883. * function ($model, $field) {
  884. * // return field value
  885. * }
  886. * ```
  887. *
  888. * For example, the following code declares four fields:
  889. *
  890. * - `email`: the field name is the same as the property name `email`;
  891. * - `firstName` and `lastName`: the field names are `firstName` and `lastName`, and their
  892. * values are obtained from the `first_name` and `last_name` properties;
  893. * - `fullName`: the field name is `fullName`. Its value is obtained by concatenating `first_name`
  894. * and `last_name`.
  895. *
  896. * ```php
  897. * return [
  898. * 'email',
  899. * 'firstName' => 'first_name',
  900. * 'lastName' => 'last_name',
  901. * 'fullName' => function ($model) {
  902. * return $model->first_name . ' ' . $model->last_name;
  903. * },
  904. * ];
  905. * ```
  906. *
  907. * In this method, you may also want to return different lists of fields based on some context
  908. * information. For example, depending on [[scenario]] or the privilege of the current application user,
  909. * you may return different sets of visible fields or filter out some fields.
  910. *
  911. * The default implementation of this method returns [[attributes()]] indexed by the same attribute names.
  912. *
  913. * @return array the list of field names or field definitions.
  914. * @see toArray()
  915. */
  916. public function fields()
  917. {
  918. $fields = $this->attributes();
  919. return array_combine($fields, $fields);
  920. }
  921. /**
  922. * Returns an iterator for traversing the attributes in the model.
  923. * This method is required by the interface [[\IteratorAggregate]].
  924. * @return ArrayIterator an iterator for traversing the items in the list.
  925. */
  926. #[\ReturnTypeWillChange]
  927. public function getIterator()
  928. {
  929. $attributes = $this->getAttributes();
  930. return new ArrayIterator($attributes);
  931. }
  932. /**
  933. * Returns whether there is an element at the specified offset.
  934. * This method is required by the SPL interface [[\ArrayAccess]].
  935. * It is implicitly called when you use something like `isset($model[$offset])`.
  936. * @param string $offset the offset to check on.
  937. * @return bool whether or not an offset exists.
  938. */
  939. #[\ReturnTypeWillChange]
  940. public function offsetExists($offset)
  941. {
  942. return isset($this->$offset);
  943. }
  944. /**
  945. * Returns 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 `$value = $model[$offset];`.
  948. * @param string $offset the offset to retrieve element.
  949. * @return mixed the element at the offset, null if no element is found at the offset
  950. */
  951. #[\ReturnTypeWillChange]
  952. public function offsetGet($offset)
  953. {
  954. return $this->$offset;
  955. }
  956. /**
  957. * Sets the element at the specified offset.
  958. * This method is required by the SPL interface [[\ArrayAccess]].
  959. * It is implicitly called when you use something like `$model[$offset] = $value;`.
  960. * @param string $offset the offset to set element
  961. * @param mixed $value the element value
  962. */
  963. #[\ReturnTypeWillChange]
  964. public function offsetSet($offset, $value)
  965. {
  966. $this->$offset = $value;
  967. }
  968. /**
  969. * Sets the element value at the specified offset to null.
  970. * This method is required by the SPL interface [[\ArrayAccess]].
  971. * It is implicitly called when you use something like `unset($model[$offset])`.
  972. * @param string $offset the offset to unset element
  973. */
  974. #[\ReturnTypeWillChange]
  975. public function offsetUnset($offset)
  976. {
  977. $this->$offset = null;
  978. }
  979. }