Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
InArray
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
4 / 4
12
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
 validate
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getInverseError
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 inArray
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
1<?php
2
3namespace Verja\Validator;
4
5use Verja\Error;
6use Verja\Validator;
7
8class InArray extends Validator
9{
10    /** @var array|string|\Traversable */
11    protected $array;
12
13    /**
14     * InArray constructor.
15     *
16     * @param array|string $array
17     */
18    public function __construct($array)
19    {
20        if (!is_array($array) && !is_string($array) && !$array instanceof \Traversable) {
21            throw new \InvalidArgumentException('$array has to be from type string, array or Traversable');
22        }
23
24        $this->array = $array;
25    }
26
27
28    /**
29     * Validate $value
30     *
31     * @param mixed $value
32     * @param array $context
33     * @return bool
34     */
35    public function validate($value, array $context = []): bool
36    {
37        if (!$this->inArray($value)) {
38            $this->error = new Error('NOT_IN_ARRAY', $value, 'value should be in array', ['array' => $this->array]);
39            return false;
40        }
41
42        return true;
43    }
44
45    public function getInverseError($value)
46    {
47        return new Error('IN_ARRAY', $value, 'value should not be in array', ['array' => $this->array]);
48    }
49
50    protected function inArray($value)
51    {
52        if (is_array($this->array)) {
53            return in_array($value, $this->array);
54        }
55
56        if (is_string($this->array)) {
57            $this->array = explode(',', $this->array);
58            return in_array($value, $this->array);
59        }
60
61        foreach ($this->array as $v) {
62            if ($value == $v) {
63                return true;
64            }
65        }
66
67        return false;
68    }
69}