Skip to content

Commit af13eda

Browse files
authored
PHPORM-68 Fix partial value un exist validator (#2568)
* PHPORM-68 Fix partial value un exist validator * escape values for regex
1 parent 6c7df45 commit af13eda

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

Diff for: src/Validation/DatabasePresenceVerifier.php

+7-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,13 @@ public function getCount($collection, $column, $value, $excludeId = null, $idCol
4343
*/
4444
public function getMultiCount($collection, $column, array $values, array $extra = [])
4545
{
46-
// Generates a regex like '/(a|b|c)/i' which can query multiple values
47-
$regex = '/('.implode('|', $values).')/i';
46+
// Nothing can match an empty array. Return early to avoid matching an empty string.
47+
if ($values === []) {
48+
return 0;
49+
}
50+
51+
// Generates a regex like '/^(a|b|c)$/i' which can query multiple values
52+
$regex = new Regex('^('.implode('|', array_map(preg_quote(...), $values)).')$', 'i');
4853

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

Diff for: tests/ValidationTest.php

+26
Original file line numberDiff line numberDiff line change
@@ -103,5 +103,31 @@ public function testExists(): void
103103
['name' => 'required|exists:users']
104104
);
105105
$this->assertFalse($validator->fails());
106+
107+
$validator = Validator::make(
108+
['name' => ['test name', 'john']], // Part of an existing value
109+
['name' => 'required|exists:users']
110+
);
111+
$this->assertTrue($validator->fails());
112+
113+
$validator = Validator::make(
114+
['name' => '(invalid regex{'],
115+
['name' => 'required|exists:users']
116+
);
117+
$this->assertTrue($validator->fails());
118+
119+
$validator = Validator::make(
120+
['name' => ['foo', '(invalid regex{']],
121+
['name' => 'required|exists:users']
122+
);
123+
$this->assertTrue($validator->fails());
124+
125+
User::create(['name' => '']);
126+
127+
$validator = Validator::make(
128+
['name' => []],
129+
['name' => 'exists:users']
130+
);
131+
$this->assertFalse($validator->fails());
106132
}
107133
}

0 commit comments

Comments
 (0)