Skip to content

Commit 453f912

Browse files
committed
refactor: extract getRegex()
1 parent 410b7a9 commit 453f912

File tree

1 file changed

+17
-25
lines changed

1 file changed

+17
-25
lines changed

system/Validation/Validation.php

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -170,16 +170,9 @@ public function run(?array $data = null, ?string $group = null, ?string $dbGroup
170170
if (strpos($field, '*') !== false) {
171171
$flattenedArray = array_flatten_with_dots($data);
172172

173-
$pattern = '/\A'
174-
. str_replace(
175-
['\.\*', '\*\.'],
176-
['\.[^.]+', '[^.]+\.'],
177-
preg_quote($field, '/')
178-
)
179-
. '\z/';
180173
$values = array_filter(
181174
$flattenedArray,
182-
static fn ($key) => preg_match($pattern, $key),
175+
static fn ($key) => preg_match($this->getRegex($field), $key),
183176
ARRAY_FILTER_USE_KEY
184177
);
185178

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

216+
/**
217+
* Returns regex pattern for key with dot array syntax.
218+
*/
219+
private function getRegex(string $field): string
220+
{
221+
return '/\A'
222+
. str_replace(
223+
['\.\*', '\*\.'],
224+
['\.[^.]+', '[^.]+\.'],
225+
preg_quote($field, '/')
226+
)
227+
. '\z/';
228+
}
229+
223230
/**
224231
* Runs the validation process, returning true or false determining whether
225232
* validation was successful or not.
@@ -823,15 +830,7 @@ private function retrievePlaceholders(string $rule, array $data): array
823830
*/
824831
public function hasError(string $field): bool
825832
{
826-
$pattern = '/\A'
827-
. str_replace(
828-
['\.\*', '\*\.'],
829-
['\.[^.]+', '[^.]+\.'],
830-
preg_quote($field, '/')
831-
)
832-
. '\z/';
833-
834-
return (bool) preg_grep($pattern, array_keys($this->getErrors()));
833+
return (bool) preg_grep($this->getRegex($field), array_keys($this->getErrors()));
835834
}
836835

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

847-
$pattern = '/\A'
848-
. str_replace(
849-
['\.\*', '\*\.'],
850-
['\.[^.]+', '[^.]+\.'],
851-
preg_quote($field, '/')
852-
)
853-
. '\z/';
854846
$errors = array_filter(
855847
$this->getErrors(),
856-
static fn ($key) => preg_match($pattern, $key),
848+
static fn ($key) => preg_match($this->getRegex($field), $key),
857849
ARRAY_FILTER_USE_KEY
858850
);
859851

0 commit comments

Comments
 (0)