Skip to content

Commit a93abc7

Browse files
committed
Validators: support for types int[], string[] etc [Closes #119]
1 parent 8b2fd88 commit a93abc7

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/Utils/Validators.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,13 @@ public static function assertField($arr, $field, $expected = NULL, $label = "ite
121121
public static function is($value, $expected)
122122
{
123123
foreach (explode('|', $expected) as $item) {
124+
if (substr($item, -2) === '[]') {
125+
if (self::everyIs($value, substr($item, 0, -2))) {
126+
return TRUE;
127+
}
128+
continue;
129+
}
130+
124131
list($type) = $item = explode(':', $item, 2);
125132
if (isset(static::$validators[$type])) {
126133
if (!call_user_func(static::$validators[$type], $value)) {

tests/Utils/Validators.is().phpt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,3 +330,29 @@ test(function () {
330330
Assert::false(Validators::is(3.14, 'iterable'));
331331
Assert::false(Validators::is(new stdClass(), 'iterable'));
332332
});
333+
334+
335+
test(function () {
336+
class Abc {}
337+
338+
Assert::true(Validators::is([], 'int[]'));
339+
Assert::true(Validators::is(new ArrayIterator([]), 'int[]'));
340+
Assert::false(Validators::is(1, 'int[]'));
341+
Assert::false(Validators::is(2.15, 'int[]'));
342+
Assert::true(Validators::is(2.15, 'float|int[]'));
343+
Assert::true(Validators::is(2.15, 'int[]|float'));
344+
Assert::true(Validators::is([1, 2, 3], 'int[]'));
345+
Assert::false(Validators::is([1, 2, 3], 'int[][]'));
346+
Assert::true(Validators::is([[1], [2, 3]], 'int[][]'));
347+
Assert::false(Validators::is([1, 2.15, 3], 'int[]'));
348+
Assert::true(Validators::is([1, 2.15, 3], 'number[]'));
349+
350+
Assert::true(Validators::is([new Abc], 'Abc[]'));
351+
Assert::false(Validators::is([new Abc, new stdClass], 'Abc[]'));
352+
353+
Assert::true(Validators::is(['ABCD', 'EFGH', 'IJKL'], 'string:4[]'));
354+
Assert::false(Validators::is(['ABCD', 'EFGH', 'IJKLM'], 'string:4[]'));
355+
356+
Assert::true(Validators::is([['ABCD', 'EFGH'], ['IJKL']], 'string:4[][]'));
357+
Assert::false(Validators::is([['ABCD', 'EFGH'], ['IJKLM']], 'string:4[][]'));
358+
});

0 commit comments

Comments
 (0)