Code Coverage |
||||||||||
Classes and Traits |
Functions and Methods |
Lines |
||||||||
Total | |
100.00% |
1 / 1 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
18 / 18 |
InArray | |
100.00% |
1 / 1 |
|
100.00% |
4 / 4 |
12 | |
100.00% |
18 / 18 |
__construct | |
100.00% |
1 / 1 |
4 | |
100.00% |
4 / 4 |
|||
validate | |
100.00% |
1 / 1 |
2 | |
100.00% |
4 / 4 |
|||
getInverseError | |
100.00% |
1 / 1 |
1 | |
100.00% |
1 / 1 |
|||
inArray | |
100.00% |
1 / 1 |
5 | |
100.00% |
9 / 9 |
<?php | |
namespace Verja\Validator; | |
use Verja\Error; | |
use Verja\Validator; | |
class InArray extends Validator | |
{ | |
/** @var array|string|\Traversable */ | |
protected $array; | |
/** | |
* InArray constructor. | |
* | |
* @param array|string $array | |
*/ | |
public function __construct($array) | |
{ | |
if (!is_array($array) && !is_string($array) && !$array instanceof \Traversable) { | |
throw new \InvalidArgumentException('$array has to be from type string, array or Traversable'); | |
} | |
$this->array = $array; | |
} | |
/** | |
* Validate $value | |
* | |
* @param mixed $value | |
* @param array $context | |
* @return bool | |
*/ | |
public function validate($value, array $context = []): bool | |
{ | |
if (!$this->inArray($value)) { | |
$this->error = new Error('NOT_IN_ARRAY', $value, 'value should be in array', ['array' => $this->array]); | |
return false; | |
} | |
return true; | |
} | |
public function getInverseError($value) | |
{ | |
return new Error('IN_ARRAY', $value, 'value should not be in array', ['array' => $this->array]); | |
} | |
protected function inArray($value) | |
{ | |
if (is_array($this->array)) { | |
return in_array($value, $this->array); | |
} | |
if (is_string($this->array)) { | |
$this->array = explode(',', $this->array); | |
return in_array($value, $this->array); | |
} | |
foreach ($this->array as $v) { | |
if ($value == $v) { | |
return true; | |
} | |
} | |
return false; | |
} | |
} |