From b25924e868cdf80944e56a76fa6eed4509d9af7b Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 16 Jul 2019 01:39:54 +0200 Subject: Allow nested rules (not and optional) --- src/Http/Validation/Validator.php | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) (limited to 'src/Http/Validation') diff --git a/src/Http/Validation/Validator.php b/src/Http/Validation/Validator.php index 0bd846bd..976f5682 100644 --- a/src/Http/Validation/Validator.php +++ b/src/Http/Validation/Validator.php @@ -22,6 +22,9 @@ class Validator 'required' => 'NotEmpty', ]; + /** @var array */ + protected $nestedRules = ['optional', 'not']; + /** * @param array $data * @param array $rules @@ -37,20 +40,38 @@ class Validator $v->with('\\Engelsystem\\Http\\Validation\\Rules', true); $value = isset($data[$key]) ? $data[$key] : null; + $values = explode('|', $values); + + $packing = []; + foreach ($this->nestedRules as $rule) { + if (in_array($rule, $values)) { + $packing[] = $rule; + } + } - foreach (explode('|', $values) as $parameters) { + $values = array_diff($values, $this->nestedRules); + foreach ($values as $parameters) { $parameters = explode(':', $parameters); $rule = array_shift($parameters); $rule = Str::camel($rule); $rule = $this->map($rule); + // To allow rules nesting + $w = $v; try { - call_user_func_array([$v, $rule], $parameters); + foreach (array_reverse(array_merge($packing, [$rule])) as $rule) { + if (!in_array($rule, $this->nestedRules)) { + call_user_func_array([$w, $rule], $parameters); + continue; + } + + $w = call_user_func_array([new RespectValidator(), $rule], [$w]); + } } catch (ComponentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } - if ($v->validate($value)) { + if ($w->validate($value)) { $this->data[$key] = $value; } else { $this->errors[$key][] = implode('.', ['validation', $key, $this->mapBack($rule)]); -- cgit v1.2.3-70-g09d2