Skip to content

Commit

Permalink
refactor: extract getRegex()
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Oct 31, 2023
1 parent 410b7a9 commit 70734bd
Showing 1 changed file with 17 additions and 25 deletions.
42 changes: 17 additions & 25 deletions system/Validation/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,16 +170,9 @@ public function run(?array $data = null, ?string $group = null, ?string $dbGroup
if (strpos($field, '*') !== false) {
$flattenedArray = array_flatten_with_dots($data);

$pattern = '/\A'
. str_replace(
['\.\*', '\*\.'],
['\.[^.]+', '[^.]+\.'],
preg_quote($field, '/')
)
. '\z/';
$values = array_filter(
$flattenedArray,
static fn ($key) => preg_match($pattern, $key),
static fn ($key) => preg_match(self::getRegex($field), $key),
ARRAY_FILTER_USE_KEY
);

Expand Down Expand Up @@ -220,6 +213,20 @@ public function run(?array $data = null, ?string $group = null, ?string $dbGroup
return false;
}

/**
* Returns regex pattern for key with dot array syntax.
*/
private static function getRegex(string $field): string
{
return '/\A'
. str_replace(
['\.\*', '\*\.'],
['\.[^.]+', '[^.]+\.'],
preg_quote($field, '/')
)
. '\z/';
}

/**
* Runs the validation process, returning true or false determining whether
* validation was successful or not.
Expand Down Expand Up @@ -823,15 +830,7 @@ private function retrievePlaceholders(string $rule, array $data): array
*/
public function hasError(string $field): bool
{
$pattern = '/\A'
. str_replace(
['\.\*', '\*\.'],
['\.[^.]+', '[^.]+\.'],
preg_quote($field, '/')
)
. '\z/';

return (bool) preg_grep($pattern, array_keys($this->getErrors()));
return (bool) preg_grep($this->getRegex($field), array_keys($this->getErrors()));
}

/**
Expand All @@ -844,16 +843,9 @@ public function getError(?string $field = null): string
$field = array_key_first($this->rules);
}

$pattern = '/\A'
. str_replace(
['\.\*', '\*\.'],
['\.[^.]+', '[^.]+\.'],
preg_quote($field, '/')
)
. '\z/';
$errors = array_filter(
$this->getErrors(),
static fn ($key) => preg_match($pattern, $key),
static fn ($key) => preg_match(self::getRegex($field), $key),
ARRAY_FILTER_USE_KEY
);

Expand Down

0 comments on commit 70734bd

Please sign in to comment.