From 5ab638f98f7a505c3385decf5f1e93bf679f857f Mon Sep 17 00:00:00 2001 From: KenFai Date: Tue, 9 Jan 2024 17:50:09 +0800 Subject: [PATCH] Use regex lazy quantifier to match first occurrence in combined validation rules (#4049) * use regex lazy quantifier to match first occurrence in combined validation rules * added test for lazy quantifier fix in RowValidator --- src/Validators/RowValidator.php | 2 +- tests/Concerns/WithValidationTest.php | 50 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/src/Validators/RowValidator.php b/src/Validators/RowValidator.php index dbcb86272..834aec311 100644 --- a/src/Validators/RowValidator.php +++ b/src/Validators/RowValidator.php @@ -134,7 +134,7 @@ private function formatRule($rules) return $rules; } - if (Str::contains($rules, 'required_') && preg_match('/(.*):(.*),(.*)/', $rules, $matches)) { + if (Str::contains($rules, 'required_') && preg_match('/(.*?):(.*),(.*)/', $rules, $matches)) { $column = Str::startsWith($matches[2], '*.') ? $matches[2] : '*.' . $matches[2]; return $matches[1] . ':' . $column . ',' . $matches[3]; diff --git a/tests/Concerns/WithValidationTest.php b/tests/Concerns/WithValidationTest.php index cc0408260..9568825ac 100644 --- a/tests/Concerns/WithValidationTest.php +++ b/tests/Concerns/WithValidationTest.php @@ -294,6 +294,56 @@ public function rules(): array $this->assertInstanceOf(ValidationException::class, $e ?? null); } + /** + * @test + */ + public function can_validate_rows_with_combined_rules_with_colons() + { + $import = new class implements ToModel, WithValidation + { + use Importable; + + /** + * @param array $row + * @return Model|null + */ + public function model(array $row) + { + return new User([ + 'name' => $row[0], + 'email' => $row[1], + 'password' => 'secret', + ]); + } + + /** + * @return array + */ + public function rules(): array + { + return [ + '1' => 'required_with:0|unique:users,email', + ]; + } + }; + + $import->import('import-users.xlsx'); + + $this->assertDatabaseHas('users', [ + 'email' => 'patrick@maatwebsite.nl', + ]); + + try { + $import->import('import-users.xlsx'); + } catch (ValidationException $e) { + $this->validateFailure($e, 1, '1', [ + 'The 1 has already been taken.', + ]); + } + + $this->assertInstanceOf(ValidationException::class, $e ?? null); + } + /** * @test */