Test Failed
Push — master ( 1eee01...3150c9 )
by Gabor
02:29
created

RangeValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 1
cts 1
cp 1
crap 1
1
<?php
2
/**
3
 * WebHemi.
4
 *
5
 * PHP version 7.1
6
 *
7
 * @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
8
 * @license   https://opensource.org/licenses/MIT The MIT License (MIT)
9
 *
10
 * @link http://www.gixx-web.com
11
 */
12
declare(strict_types = 1);
13
14
namespace WebHemi\Validator;
15
16
/**
17
 * class RangeValidator.
18
 */
19
class RangeValidator implements ValidatorInterface
20
{
21
    /**
22
     * @var array
23
     */
24
    private $availableValues;
25
    /**
26
     * @var bool
27
     */
28
    private $validateKeys;
29
    /**
30
     * @var array
31
     */
32
    private $errors;
33
    /**
34
     * @var array
35
     */
36
    private $validData;
37
38
    /**
39
     * RangeValidator constructor.
40
     *
41
     * @param array $options
42
     */
43
    public function __construct(array $options = [])
44 3
    {
45
        $this->setOptions($options);
46 3
    }
47 3
48 3
    /**
49
     * Set validator options.
50
     *
51
     * @param array $options
52
     */
53
    public function setOptions(array $options) : void
54
    {
55
        $this->availableValues = isset($options['availableValues']) && is_array($options['availableValues'])
56 2
            ? array_values($options['availableValues'])
57
            : [];
58 2
        $this->validateKeys = (bool) ($options['validateKeys'] ?? false);
59 2
    }
60
61 2
    /**
62 2
     * Validates data.
63 2
     *
64
     * @param  array $values
65
     * @return bool
66 2
     */
67
    public function validate(array $values) : bool
68 2
    {
69
        $data = $this->validateKeys ? array_keys($values) : array_values($values);
70
        $diff = array_diff($data, $this->availableValues);
71
72
        if (!empty($diff)) {
73
            $this->errors[] = sprintf("Some data is out of range: %s", implode(', ', $diff));
74
            return false;
75
        }
76 2
77
        $this->validData = $values;
78 2
79
        return true;
80
    }
81
82
    /**
83
     * Retrieve valid data.
84
     *
85
     * @return array
86 2
     */
87
    public function getValidData() : array
88 2
    {
89
        return $this->validData;
90
    }
91
92
    /**
93
     * Gets errors from validation.
94
     *
95
     * @return array
96
     */
97
    public function getErrors() : array
98
    {
99
        return $this->errors;
100
    }
101
}
102