Skip to content

Commit

Permalink
fix Validation.php
Browse files Browse the repository at this point in the history
  • Loading branch information
amirfaramarzi committed Jul 17, 2024
1 parent c5bd054 commit 3db7438
Showing 1 changed file with 59 additions and 55 deletions.
114 changes: 59 additions & 55 deletions src/Validation/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,64 +27,13 @@ public static function setInstance(): void

public static function getInstance(): self
{
self::$instance->rules = [];
self::$instance->errors = [];
self::$instance->data = [];

return self::$instance;
}

protected function existsData(array $array, string|int $key): bool
{
return array_key_exists($key, $array);
}

protected function collapseData(array $array): array
{
$results = [];

foreach ($array as $values) {
$results[] = $values;
}

return array_merge([], ...$results);
}

protected function getData(mixed $target, string|array|int|null $key, mixed $default = null): mixed
{
if (is_null($key)) {
return $target;
}

$key = is_array($key) ? $key : explode('.', $key);

foreach ($key as $i => $segment) {
unset($key[$i]);

if (is_null($segment)) {
return $target;
}

if ($segment === '*') {
if (! is_array($target)) {
return value($default);
}

$result = [];

foreach ($target as $item) {
$result[] = $this->getData($item, $key);
}

return in_array('*', $key) ? $this->collapseData($result) : $result;
}

if (is_array($target) && $this->existsData($target, $segment)) {
$target = $target[$segment];
} else {
return value($default);
}
}

return $target;
}

public function validate(array $data , array $rules): self
{
$this->data = $data;
Expand Down Expand Up @@ -156,4 +105,59 @@ public function firstError(): array
{
return $this->errors[0];
}

protected function existsData(array $array, string|int $key): bool
{
return array_key_exists($key, $array);
}

protected function collapseData(array $array): array
{
$results = [];

foreach ($array as $values) {
$results[] = $values;
}

return array_merge([], ...$results);
}

protected function getData(mixed $target, string|array|int|null $key, mixed $default = null): mixed
{
if (is_null($key)) {
return $target;
}

$key = is_array($key) ? $key : explode('.', $key);

foreach ($key as $i => $segment) {
unset($key[$i]);

if (is_null($segment)) {
return $target;
}

if ($segment === '*') {
if (! is_array($target)) {
return value($default);
}

$result = [];

foreach ($target as $item) {
$result[] = $this->getData($item, $key);
}

return in_array('*', $key) ? $this->collapseData($result) : $result;
}

if (is_array($target) && $this->existsData($target, $segment)) {
$target = $target[$segment];
} else {
return value($default);
}
}

return $target;
}
}

0 comments on commit 3db7438

Please sign in to comment.