From 0a3821938ab13e90e794907ab2d4433e30987a32 Mon Sep 17 00:00:00 2001 From: Amir Date: Thu, 9 Sep 2021 10:47:00 +0430 Subject: [PATCH] bug fix in src/Validation.php --- src/Validation.php | 42 +++++++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/src/Validation.php b/src/Validation.php index 1a66b68..291eccd 100644 --- a/src/Validation.php +++ b/src/Validation.php @@ -2,6 +2,8 @@ namespace Tower; +use ArrayAccess; +use Illuminate\Support\Enumerable; use Tower\Validation\Rules; class Validation @@ -21,6 +23,19 @@ public function __construct(array $data , array $rules) $this->validate(); } + protected function exists(Enumerable|ArrayAccess|array $array, string $key): bool + { + if ($array instanceof Enumerable) { + return $array->has($key); + } + + if ($array instanceof ArrayAccess) { + return $array->offsetExists($key); + } + + return array_key_exists($key, $array); + } + protected function collapse(array $array): array { $results = []; @@ -32,10 +47,10 @@ protected function collapse(array $array): array return array_merge([], ...$results); } - protected function get(array $array, array|string|null $key, ?string $default = null): string|int|bool|array|float|null + protected function get(string|int|bool|array|float $target, array|string|null $key, string|int|bool|array|float|null $default = null): string|int|bool|array|float|null { if (is_null($key)) { - return $array; + return $target; } $key = is_array($key) ? $key : explode('.', $key); @@ -44,27 +59,27 @@ protected function get(array $array, array|string|null $key, ?string $default = unset($key[$i]); if (is_null($segment)) { - return $array; + return $target; } if ($segment === '*') { $result = []; - foreach ($array as $item) { + foreach ($target as $item) { $result[] = $this->get($item, $key); } return in_array('*', $key) ? $this->collapse($result) : $result; } - if (array_key_exists($segment, $array)) { - $array = $array[$segment]; + if (array_key_exists($segment, $target)) { + $target = $target[$segment]; } else { return value($default); } } - return $array; + return $target; } protected function validate(): void @@ -74,6 +89,11 @@ protected function validate(): void $indexExplode = explode('.' , $index); count($indexExplode) > 1 ? $indexLocal = last($indexExplode) : $indexLocal = $index; + if ($indexLocal == '*'){ + $lastKey = array_key_last($indexExplode); + $indexLocal = $indexExplode[$lastKey - 1]; + } + foreach ($rule as $item) { $itemExplode = explode(':' , $item); $item = $itemExplode[0]; @@ -101,6 +121,14 @@ public function hasError(): bool return true; } + public function hasMessage(): bool + { + if (empty($this->errors)) + return false; + + return true; + } + public function getMessages(): array { return array_column($this->errors , 'message');