|
- <?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);
- }
- }
|