Model.php 39 KB

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