|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 |
- <?php
-
-
- namespace yii\base;
-
- use yii\validators\Validator;
-
-
- class DynamicModel extends Model
- {
- private $_attributes = [];
-
-
-
-
- public function __construct(array $attributes = [], $config = [])
- {
- foreach ($attributes as $name => $value) {
- if (is_int($name)) {
- $this->_attributes[$value] = null;
- } else {
- $this->_attributes[$name] = $value;
- }
- }
- parent::__construct($config);
- }
-
-
-
- public function __get($name)
- {
- if (array_key_exists($name, $this->_attributes)) {
- return $this->_attributes[$name];
- } else {
- return parent::__get($name);
- }
- }
-
-
-
- public function __set($name, $value)
- {
- if (array_key_exists($name, $this->_attributes)) {
- $this->_attributes[$name] = $value;
- } else {
- parent::__set($name, $value);
- }
- }
-
-
-
- public function __isset($name)
- {
- if (array_key_exists($name, $this->_attributes)) {
- return isset($this->_attributes[$name]);
- } else {
- return parent::__isset($name);
- }
- }
-
-
-
- public function __unset($name)
- {
- if (array_key_exists($name, $this->_attributes)) {
- unset($this->_attributes[$name]);
- } else {
- parent::__unset($name);
- }
- }
-
-
-
- public function defineAttribute($name, $value = null)
- {
- $this->_attributes[$name] = $value;
- }
-
-
-
- public function undefineAttribute($name)
- {
- unset($this->_attributes[$name]);
- }
-
-
-
- public function addRule($attributes, $validator, $options = [])
- {
- $validators = $this->getValidators();
- $validators->append(Validator::createValidator($validator, $this, (array) $attributes, $options));
-
- return $this;
- }
-
-
-
- public static function validateData(array $data, $rules = [])
- {
-
- $model = new static($data);
- if (!empty($rules)) {
- $validators = $model->getValidators();
- foreach ($rules as $rule) {
- if ($rule instanceof Validator) {
- $validators->append($rule);
- } elseif (is_array($rule) && isset($rule[0], $rule[1])) {
- $validator = Validator::createValidator($rule[1], $model, (array) $rule[0], array_slice($rule, 2));
- $validators->append($validator);
- } else {
- throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
- }
- }
- }
-
- $model->validate();
-
- return $model;
- }
-
-
-
- public function attributes()
- {
- return array_keys($this->_attributes);
- }
- }
|