Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
IsArray | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
10 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
validate | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
8 | |||
getInverseError | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | namespace Verja\Validator; |
4 | |
5 | use Verja\Error; |
6 | use Verja\Validator; |
7 | |
8 | class IsArray extends Validator |
9 | { |
10 | const TYPE_ANY = 'any'; |
11 | const TYPE_ASSOC = 'assoc'; |
12 | const TYPE_INDEX = 'index'; |
13 | |
14 | protected $type; |
15 | |
16 | /** |
17 | * IsArray constructor. |
18 | * |
19 | * @param string $type 'any' (default), 'assoc' or 'index' |
20 | */ |
21 | public function __construct(string $type = self::TYPE_ANY) |
22 | { |
23 | $this->type = $type; |
24 | } |
25 | |
26 | /** |
27 | * Validate $value |
28 | * |
29 | * @param mixed $value |
30 | * @param array $context |
31 | * @return bool |
32 | */ |
33 | public function validate($value, array $context = []): bool |
34 | { |
35 | $parameters = ['type' => $this->type]; |
36 | |
37 | if (!is_array($value)) { |
38 | $this->error = new Error('NO_ARRAY', $value, 'value should be an array', $parameters); |
39 | return false; |
40 | } elseif ($this->type !== self::TYPE_ANY) { |
41 | $isIndexed = empty($value) || array_keys($value) === range(0, count($value) -1); |
42 | if ($this->type === self::TYPE_ASSOC && $isIndexed) { |
43 | $this->error = new Error('NO_ASSOC_ARRAY', $value, 'value should be an associative array', $parameters); |
44 | return false; |
45 | } elseif ($this->type === self::TYPE_INDEX && !$isIndexed) { |
46 | $this->error = new Error('NO_INDEX_ARRAY', $value, 'value should be an indexed array', $parameters); |
47 | return false; |
48 | } |
49 | } |
50 | |
51 | return true; |
52 | } |
53 | |
54 | public function getInverseError($value) |
55 | { |
56 | return new Error('IS_ARRAY', $value, 'value should not be an array'); |
57 | } |
58 | } |