IsInArray   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 13
c 1
b 0
f 0
dl 0
loc 40
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A check() 0 10 4
A haystack() 0 10 2
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
Are you sure the doc-type for parameter $value is correct as it would always require null to be passed?
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
introduced by
The condition is_array($this->haystack) is always true.
Loading history...
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