Skip to content

Commit dd03d7e

Browse files
validate a nested rules (object)
1 parent 8c0a723 commit dd03d7e

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

src/Utils.php

+25
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,29 @@ public static function canBeString(mixed $value): bool
1616
{
1717
return $value === null || is_scalar($value) || $value instanceof Stringable;
1818
}
19+
20+
/**
21+
* Get item from array using dot notation.
22+
*
23+
* @param array<string, mixed> $array
24+
* @param string $key
25+
* @param mixed $default
26+
* @return mixed
27+
*/
28+
public static function array_get(array $array, string $key, mixed $default = null): mixed
29+
{
30+
if (array_key_exists($key, $array)) {
31+
return $array[$key];
32+
}
33+
34+
foreach (explode('.', $key) as $segment) {
35+
if (!is_array($array) || !array_key_exists($segment, $array)) {
36+
return $default;
37+
}
38+
39+
$array = $array[$segment];
40+
}
41+
42+
return $array;
43+
}
1944
}

src/Validator.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,8 @@ public static function initMultiple(array $values, array $entries): array|true
9090
$result = [];
9191

9292
foreach ($entries as $key => $rules) {
93-
$errors = static::validateMultipleRules($values[$key] ?? null, $rules);
93+
$value = Utils::array_get($values, $key);
94+
$errors = static::validateMultipleRules($value, $rules);
9495

9596
if (count($errors)) {
9697
$result[$key] = $errors;

tests/ValidatorTest.php

+16
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,22 @@ public function validate(mixed $value, mixed ...$params): bool
6363
expect(Validator::initMultiple($entries, $validations))->toBe(true);
6464
});
6565

66+
it('can validate a nested rules (object)', function () {
67+
$entries = [
68+
'user' => [
69+
'name' => 'John Doe',
70+
'email' => '[email protected]',
71+
],
72+
];
73+
74+
$validations = [
75+
'user.name' => 'required|min:5|max:255',
76+
'user.email' => 'required|email|min:5|max:255',
77+
];
78+
79+
expect(Validator::initMultiple($entries, $validations))->toBe(true);
80+
});
81+
6682
it('can change the default error message', function () {
6783
Validator::setMessages([EqualsOne::class => 'test']);
6884
expect(Validator::init(2)->equalsOne()->getErrors())

0 commit comments

Comments
 (0)