Skip to content

Commit

Permalink
Use regex lazy quantifier to match first occurrence in combined valid…
Browse files Browse the repository at this point in the history
…ation rules (#4049)

* use regex lazy quantifier to match first occurrence in combined validation rules

* added test for lazy quantifier fix in RowValidator
  • Loading branch information
kenfai authored Jan 9, 2024
1 parent f3cce83 commit 5ab638f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Validators/RowValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
50 changes: 50 additions & 0 deletions tests/Concerns/WithValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' => '[email protected]',
]);

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
*/
Expand Down

0 comments on commit 5ab638f

Please sign in to comment.