From 4913acc1d6bab342e45a95fe14afd1866e3b23c9 Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 31 Oct 2023 11:22:33 +0900 Subject: [PATCH] refactor: extract getRegex() --- system/Validation/Validation.php | 42 +++++++++++++------------------- 1 file changed, 17 insertions(+), 25 deletions(-) diff --git a/system/Validation/Validation.php b/system/Validation/Validation.php index f8c64e63ab3c..b1612481b97b 100644 --- a/system/Validation/Validation.php +++ b/system/Validation/Validation.php @@ -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 ); @@ -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. @@ -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(self::getRegex($field), array_keys($this->getErrors())); } /** @@ -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 );