diff --git a/src/Attribute.php b/src/Attribute.php index ebd7a11..c3626a1 100644 --- a/src/Attribute.php +++ b/src/Attribute.php @@ -47,8 +47,10 @@ public function __construct( $this->validation = $validation; $this->alias = $alias; $this->key = $key; + $rule_number = 0; foreach ($rules as $rule) { - $this->addRule($rule); + $this->addRule($rule, $rule_number); + $rule_number++; } } @@ -125,11 +127,11 @@ public function getOtherAttributes(): array * @param \Rakit\Validation\Rule $rule * @return void */ - public function addRule(Rule $rule) + public function addRule(Rule $rule, int $rule_number) { $rule->setAttribute($this); $rule->setValidation($this->validation); - $this->rules[$rule->getKey()] = $rule; + $this->rules[$rule->getKey() . (string)$rule_number] = $rule; } /** diff --git a/src/Rules/Length.php b/src/Rules/Length.php new file mode 100644 index 0000000..ebe3457 --- /dev/null +++ b/src/Rules/Length.php @@ -0,0 +1,31 @@ +requireParameters($this->fillableParams); + + $length = (int) $this->parameter('length'); + + return strlen((string) $value) == $length; + } +} diff --git a/src/Rules/LengthIn.php b/src/Rules/LengthIn.php new file mode 100644 index 0000000..ad30131 --- /dev/null +++ b/src/Rules/LengthIn.php @@ -0,0 +1,61 @@ +params + * + * @param array $params + * @return self + */ + public function fillParameters(array $params): Rule + { + if (count($params) == 1 && is_array($params[0])) { + $params = $params[0]; + } + $this->params['allowed_values'] = $params; + return $this; + } + + /** + * Set strict value + * + * @param bool $strict + * @return void + */ + public function strict(bool $strict = true) + { + $this->strict = $strict; + } + + /** + * Check $value is existed + * + * @param mixed $value + * @return bool + */ + public function check($value): bool + { + $this->requireParameters(['allowed_values']); + + $allowedValues = $this->parameter('allowed_values'); + + return in_array( strlen((string)$value), $allowedValues, $this->strict); + } +} diff --git a/src/Validator.php b/src/Validator.php index dfa19c5..0a87d01 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -162,6 +162,8 @@ protected function registerBaseValidators() 'defaults' => new Rules\Defaults, 'default' => new Rules\Defaults, // alias of defaults 'nullable' => new Rules\Nullable, + 'length' => new Rules\Length, + 'length_in' => new Rules\LengthIn, ]; foreach ($baseValidator as $key => $validator) {