Model.php 37 KB

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