Skip to content

Commit

Permalink
PHPORM-68 Fix partial value un exist validator (#2568)
Browse files Browse the repository at this point in the history
* PHPORM-68 Fix partial value un exist validator

* escape values for regex
  • Loading branch information
GromNaN authored Aug 23, 2023
1 parent 6c7df45 commit af13eda
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Validation/DatabasePresenceVerifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,13 @@ public function getCount($collection, $column, $value, $excludeId = null, $idCol
*/
public function getMultiCount($collection, $column, array $values, array $extra = [])
{
// Generates a regex like '/(a|b|c)/i' which can query multiple values
$regex = '/('.implode('|', $values).')/i';
// Nothing can match an empty array. Return early to avoid matching an empty string.
if ($values === []) {
return 0;
}

// Generates a regex like '/^(a|b|c)$/i' which can query multiple values
$regex = new Regex('^('.implode('|', array_map(preg_quote(...), $values)).')$', 'i');

$query = $this->table($collection)->where($column, 'regex', $regex);

Expand Down
26 changes: 26 additions & 0 deletions tests/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,5 +103,31 @@ public function testExists(): void
['name' => 'required|exists:users']
);
$this->assertFalse($validator->fails());

$validator = Validator::make(
['name' => ['test name', 'john']], // Part of an existing value
['name' => 'required|exists:users']
);
$this->assertTrue($validator->fails());

$validator = Validator::make(
['name' => '(invalid regex{'],
['name' => 'required|exists:users']
);
$this->assertTrue($validator->fails());

$validator = Validator::make(
['name' => ['foo', '(invalid regex{']],
['name' => 'required|exists:users']
);
$this->assertTrue($validator->fails());

User::create(['name' => '']);

$validator = Validator::make(
['name' => []],
['name' => 'exists:users']
);
$this->assertFalse($validator->fails());
}
}

0 comments on commit af13eda

Please sign in to comment.