|
- <?php
-
-
- namespace yii\validators;
-
- use yii\base\InvalidConfigException;
- use Yii;
- use yii\base\Model;
-
-
- class EachValidator extends Validator
- {
-
-
- public $rule;
-
-
- public $allowMessageFromRule = true;
-
-
-
- private $_validator;
-
-
-
-
- public function init()
- {
- parent::init();
- if ($this->message === null) {
- $this->message = Yii::t('yii', '{attribute} is invalid.');
- }
- }
-
-
-
- private function getValidator($model = null)
- {
- if ($this->_validator === null) {
- $this->_validator = $this->createEmbeddedValidator($model);
- }
- return $this->_validator;
- }
-
-
-
- private function createEmbeddedValidator($model)
- {
- $rule = $this->rule;
- if ($rule instanceof Validator) {
- return $rule;
- } elseif (is_array($rule) && isset($rule[0])) {
- if (!is_object($model)) {
- $model = new Model();
- }
- return Validator::createValidator($rule[0], $model, $this->attributes, array_slice($rule, 1));
- } else {
- throw new InvalidConfigException('Invalid validation rule: a rule must be an array specifying validator type.');
- }
- }
-
-
-
- public function validateAttribute($model, $attribute)
- {
- $value = $model->$attribute;
- if (!is_array($value)) {
- $this->addError($model, $attribute, $this->message, []);
- return;
- }
-
- $validator = $this->getValidator($model);
-
- $originalErrors = $model->getErrors($attribute);
- $filteredValue = [];
- foreach ($value as $k => $v) {
- $model->$attribute = $v;
- if (!$validator->skipOnEmpty || !$validator->isEmpty($v)) {
- $validator->validateAttribute($model, $attribute);
- }
- $filteredValue[$k] = $model->$attribute;
- if ($model->hasErrors($attribute)) {
- $validationErrors = $model->getErrors($attribute);
- $model->clearErrors($attribute);
- if (!empty($originalErrors)) {
- $model->addErrors([$attribute => $originalErrors]);
- }
- if ($this->allowMessageFromRule) {
- $model->addErrors([$attribute => $validationErrors]);
- } else {
- $this->addError($model, $attribute, $this->message, ['value' => $v]);
- }
- $model->$attribute = $value;
- return;
- }
- }
- $model->$attribute = $filteredValue;
- }
-
-
-
- protected function validateValue($value)
- {
- if (!is_array($value)) {
- return [$this->message, []];
- }
-
- $validator = $this->getValidator();
- foreach ($value as $v) {
- if ($validator->skipOnEmpty && $validator->isEmpty($v)) {
- continue;
- }
- $result = $validator->validateValue($v);
- if ($result !== null) {
- if ($this->allowMessageFromRule) {
- $result[1]['value'] = $v;
- return $result;
- } else {
- return [$this->message, ['value' => $v]];
- }
- }
- }
-
- return null;
- }
- }
|