diff --git a/system/Validation/Rules.php b/system/Validation/Rules.php index 40a5955b157d..c8284629d3b3 100644 --- a/system/Validation/Rules.php +++ b/system/Validation/Rules.php @@ -11,6 +11,7 @@ namespace CodeIgniter\Validation; +use CodeIgniter\Validation\StrictRules\Rules as StrictRules; use Config\Database; use InvalidArgumentException; @@ -19,6 +20,15 @@ */ class Rules { + private ?StrictRules $strictRules = null; + + private function createStrictRules(): void + { + if ($this->strictRules === null) { + $this->strictRules = new StrictRules(); + } + } + /** * The value does not match another field in $data. * @@ -125,21 +135,9 @@ public function in_list(?string $value, string $list): bool */ public function is_unique(?string $str, string $field, array $data): bool { - [$field, $ignoreField, $ignoreValue] = array_pad(explode(',', $field), 3, null); - - sscanf($field, '%[^.].%[^.]', $table, $field); - - $row = Database::connect($data['DBGroup'] ?? null) - ->table($table) - ->select('1') - ->where($field, $str) - ->limit(1); - - if (! empty($ignoreField) && ! empty($ignoreValue) && ! preg_match('/^\{(\w+)\}$/', $ignoreValue)) { - $row = $row->where("{$ignoreField} !=", $ignoreValue); - } + $this->createStrictRules(); - return $row->get()->getRow() === null; + return $this->strictRules->is_unique($str, $field, $data); } /** diff --git a/system/Validation/StrictRules/Rules.php b/system/Validation/StrictRules/Rules.php index 47dbee9b5ae7..1091b319f43f 100644 --- a/system/Validation/StrictRules/Rules.php +++ b/system/Validation/StrictRules/Rules.php @@ -151,7 +151,25 @@ public function in_list($value, string $list): bool */ public function is_unique($str, string $field, array $data): bool { - return $this->nonStrictRules->is_unique($str, $field, $data); + [$field, $ignoreField, $ignoreValue] = array_pad( + explode(',', $field), + 3, + null + ); + + sscanf($field, '%[^.].%[^.]', $table, $field); + + $row = Database::connect($data['DBGroup'] ?? null) + ->table($table) + ->select('1') + ->where($field, $str) + ->limit(1); + + if (! empty($ignoreField) && ! empty($ignoreValue) && ! preg_match('/^\{(\w+)\}$/', $ignoreValue)) { + $row = $row->where("{$ignoreField} !=", $ignoreValue); + } + + return $row->get()->getRow() === null; } /**