Skip to content

Commit

Permalink
bug fix in src/Validation.php
Browse files Browse the repository at this point in the history
  • Loading branch information
amirfaramarzi committed Sep 9, 2021
1 parent ac9fca5 commit 0a38219
Showing 1 changed file with 35 additions and 7 deletions.
42 changes: 35 additions & 7 deletions src/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Tower;

use ArrayAccess;
use Illuminate\Support\Enumerable;
use Tower\Validation\Rules;

class Validation
Expand All @@ -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 = [];
Expand All @@ -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);
Expand All @@ -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
Expand All @@ -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];
Expand Down Expand Up @@ -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');
Expand Down

0 comments on commit 0a38219

Please sign in to comment.