|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133 |
- <?php
-
-
- namespace yii\validators;
-
- use Yii;
- use yii\base\InvalidConfigException;
- use yii\helpers\ArrayHelper;
-
-
- class RangeValidator extends Validator
- {
-
-
- public $range;
-
-
- public $strict = false;
-
-
- public $not = false;
-
-
- public $allowArray = false;
-
-
-
-
- public function init()
- {
- parent::init();
- if (!is_array($this->range)
- && !($this->range instanceof \Closure)
- && !($this->range instanceof \Traversable)
- ) {
- throw new InvalidConfigException('The "range" property must be set.');
- }
- if ($this->message === null) {
- $this->message = Yii::t('yii', '{attribute} is invalid.');
- }
- }
-
-
-
- protected function validateValue($value)
- {
- $in = false;
-
- if ($this->allowArray
- && ($value instanceof \Traversable || is_array($value))
- && ArrayHelper::isSubset($value, $this->range, $this->strict)
- ) {
- $in = true;
- }
-
- if (!$in && ArrayHelper::isIn($value, $this->range, $this->strict)) {
- $in = true;
- }
-
- return $this->not !== $in ? null : [$this->message, []];
- }
-
-
-
- public function validateAttribute($model, $attribute)
- {
- if ($this->range instanceof \Closure) {
- $this->range = call_user_func($this->range, $model, $attribute);
- }
- parent::validateAttribute($model, $attribute);
- }
-
-
-
- public function clientValidateAttribute($model, $attribute, $view)
- {
- if ($this->range instanceof \Closure) {
- $this->range = call_user_func($this->range, $model, $attribute);
- }
-
- $range = [];
- foreach ($this->range as $value) {
- $range[] = (string) $value;
- }
- $options = [
- 'range' => $range,
- 'not' => $this->not,
- 'message' => Yii::$app->getI18n()->format($this->message, [
- 'attribute' => $model->getAttributeLabel($attribute),
- ], Yii::$app->language),
- ];
- if ($this->skipOnEmpty) {
- $options['skipOnEmpty'] = 1;
- }
- if ($this->allowArray) {
- $options['allowArray'] = 1;
- }
-
- ValidationAsset::register($view);
-
- return 'yii.validation.range(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
- }
- }
|