Falseclock /
service-layer
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * @author Nurlan Mukhanov <[email protected]> |
||
| 4 | * @copyright 2022 Nurlan Mukhanov |
||
| 5 | * @license https://en.wikipedia.org/wiki/MIT_License MIT License |
||
| 6 | * @link https://github.com/Falseclock/service-layer |
||
| 7 | */ |
||
| 8 | |||
| 9 | declare(strict_types=1); |
||
| 10 | |||
| 11 | namespace Falseclock\Service\Validation\Validators; |
||
| 12 | |||
| 13 | use Falseclock\Service\Validation\ValidationException; |
||
| 14 | use Falseclock\Service\Validation\ValidatorImpl; |
||
| 15 | |||
| 16 | class IsInArray extends ValidatorImpl |
||
| 17 | { |
||
| 18 | public const ERROR_MULTI_DIMENSIONAL = "Array must not be multi dimensional"; |
||
| 19 | public const ERROR_NO_ARRAY_DEFINED = "No haystack array defined"; |
||
| 20 | /** @var array */ |
||
| 21 | protected $haystack; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * @param null $value |
||
|
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
| 25 | * @return bool |
||
| 26 | * @throws ValidationException |
||
| 27 | */ |
||
| 28 | public function check($value = null): bool |
||
| 29 | { |
||
| 30 | if (is_null($value) && $this->nullable) { |
||
| 31 | return true; |
||
| 32 | } |
||
| 33 | |||
| 34 | if (!is_array($this->haystack)) |
||
|
0 ignored issues
–
show
|
|||
| 35 | throw new ValidationException(self::ERROR_NO_ARRAY_DEFINED); |
||
| 36 | |||
| 37 | return in_array($value, $this->haystack, true); |
||
| 38 | } |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @param array $array |
||
| 42 | * |
||
| 43 | * @return $this |
||
| 44 | * @throws ValidationException |
||
| 45 | */ |
||
| 46 | public function haystack(array $array): IsInArray |
||
| 47 | { |
||
| 48 | // Check for multi dimensional array |
||
| 49 | if (count($array) != count($array, COUNT_RECURSIVE)) { |
||
| 50 | throw new ValidationException(self::ERROR_MULTI_DIMENSIONAL); |
||
| 51 | } |
||
| 52 | |||
| 53 | $this->haystack = $array; |
||
| 54 | |||
| 55 | return $this; |
||
| 56 | } |
||
| 57 | } |
||
| 58 |