DynamicModel.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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\validators\Validator;
  9. /**
  10. * DynamicModel is a model class primarily used to support ad hoc data validation.
  11. *
  12. * The typical usage of DynamicModel is as follows,
  13. *
  14. * ```php
  15. * public function actionSearch($name, $email)
  16. * {
  17. * $model = DynamicModel::validateData(compact('name', 'email'), [
  18. * [['name', 'email'], 'string', 'max' => 128],
  19. * ['email', 'email'],
  20. * ]);
  21. * if ($model->hasErrors()) {
  22. * // validation fails
  23. * } else {
  24. * // validation succeeds
  25. * }
  26. * }
  27. * ```
  28. *
  29. * The above example shows how to validate `$name` and `$email` with the help of DynamicModel.
  30. * The [[validateData()]] method creates an instance of DynamicModel, defines the attributes
  31. * using the given data (`name` and `email` in this example), and then calls [[Model::validate()]].
  32. *
  33. * You can check the validation result by [[hasErrors()]], like you do with a normal model.
  34. * You may also access the dynamic attributes defined through the model instance, e.g.,
  35. * `$model->name` and `$model->email`.
  36. *
  37. * Alternatively, you may use the following more "classic" syntax to perform ad-hoc data validation:
  38. *
  39. * ```php
  40. * $model = new DynamicModel(compact('name', 'email'));
  41. * $model->addRule(['name', 'email'], 'string', ['max' => 128])
  42. * ->addRule('email', 'email')
  43. * ->validate();
  44. * ```
  45. *
  46. * DynamicModel implements the above ad-hoc data validation feature by supporting the so-called
  47. * "dynamic attributes". It basically allows an attribute to be defined dynamically through its constructor
  48. * or [[defineAttribute()]].
  49. *
  50. * @author Qiang Xue <qiang.xue@gmail.com>
  51. * @since 2.0
  52. */
  53. class DynamicModel extends Model
  54. {
  55. private $_attributes = [];
  56. /**
  57. * Constructors.
  58. * @param array $attributes the dynamic attributes (name-value pairs, or names) being defined
  59. * @param array $config the configuration array to be applied to this object.
  60. */
  61. public function __construct(array $attributes = [], $config = [])
  62. {
  63. foreach ($attributes as $name => $value) {
  64. if (is_int($name)) {
  65. $this->_attributes[$value] = null;
  66. } else {
  67. $this->_attributes[$name] = $value;
  68. }
  69. }
  70. parent::__construct($config);
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function __get($name)
  76. {
  77. if ($this->hasAttribute($name)) {
  78. return $this->_attributes[$name];
  79. }
  80. return parent::__get($name);
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function __set($name, $value)
  86. {
  87. if ($this->hasAttribute($name)) {
  88. $this->_attributes[$name] = $value;
  89. } else {
  90. parent::__set($name, $value);
  91. }
  92. }
  93. /**
  94. * {@inheritdoc}
  95. */
  96. public function __isset($name)
  97. {
  98. if ($this->hasAttribute($name)) {
  99. return isset($this->_attributes[$name]);
  100. }
  101. return parent::__isset($name);
  102. }
  103. /**
  104. * {@inheritdoc}
  105. */
  106. public function __unset($name)
  107. {
  108. if ($this->hasAttribute($name)) {
  109. unset($this->_attributes[$name]);
  110. } else {
  111. parent::__unset($name);
  112. }
  113. }
  114. /**
  115. * {@inheritdoc}
  116. */
  117. public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
  118. {
  119. return parent::canGetProperty($name, $checkVars, $checkBehaviors) || $this->hasAttribute($name);
  120. }
  121. /**
  122. * {@inheritdoc}
  123. */
  124. public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
  125. {
  126. return parent::canSetProperty($name, $checkVars, $checkBehaviors) || $this->hasAttribute($name);
  127. }
  128. /**
  129. * Returns a value indicating whether the model has an attribute with the specified name.
  130. * @param string $name the name of the attribute
  131. * @return bool whether the model has an attribute with the specified name.
  132. * @since 2.0.16
  133. */
  134. public function hasAttribute($name)
  135. {
  136. return array_key_exists($name, $this->_attributes);
  137. }
  138. /**
  139. * Defines an attribute.
  140. * @param string $name the attribute name
  141. * @param mixed $value the attribute value
  142. */
  143. public function defineAttribute($name, $value = null)
  144. {
  145. $this->_attributes[$name] = $value;
  146. }
  147. /**
  148. * Undefines an attribute.
  149. * @param string $name the attribute name
  150. */
  151. public function undefineAttribute($name)
  152. {
  153. unset($this->_attributes[$name]);
  154. }
  155. /**
  156. * Adds a validation rule to this model.
  157. * You can also directly manipulate [[validators]] to add or remove validation rules.
  158. * This method provides a shortcut.
  159. * @param string|array $attributes the attribute(s) to be validated by the rule
  160. * @param mixed $validator the validator for the rule.This can be a built-in validator name,
  161. * a method name of the model class, an anonymous function, or a validator class name.
  162. * @param array $options the options (name-value pairs) to be applied to the validator
  163. * @return $this the model itself
  164. */
  165. public function addRule($attributes, $validator, $options = [])
  166. {
  167. $validators = $this->getValidators();
  168. $validators->append(Validator::createValidator($validator, $this, (array)$attributes, $options));
  169. return $this;
  170. }
  171. /**
  172. * Validates the given data with the specified validation rules.
  173. * This method will create a DynamicModel instance, populate it with the data to be validated,
  174. * create the specified validation rules, and then validate the data using these rules.
  175. * @param array $data the data (name-value pairs) to be validated
  176. * @param array $rules the validation rules. Please refer to [[Model::rules()]] on the format of this parameter.
  177. * @return static the model instance that contains the data being validated
  178. * @throws InvalidConfigException if a validation rule is not specified correctly.
  179. */
  180. public static function validateData(array $data, $rules = [])
  181. {
  182. /* @var $model DynamicModel */
  183. $model = new static($data);
  184. if (!empty($rules)) {
  185. $validators = $model->getValidators();
  186. foreach ($rules as $rule) {
  187. if ($rule instanceof Validator) {
  188. $validators->append($rule);
  189. } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
  190. $validator = Validator::createValidator($rule[1], $model, (array)$rule[0], array_slice($rule, 2));
  191. $validators->append($validator);
  192. } else {
  193. throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
  194. }
  195. }
  196. }
  197. $model->validate();
  198. return $model;
  199. }
  200. /**
  201. * {@inheritdoc}
  202. */
  203. public function attributes()
  204. {
  205. return array_keys($this->_attributes);
  206. }
  207. }