Passed
Push — master ( 5c25b8...502eee )
by Gabor
05:16
created

RangeValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 2
1
<?php
2
/**
3
 * WebHemi.
4
 *
5
 * PHP version 7.1
6
 *
7
 * @copyright 2012 - 2017 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
    /** @var array  */
22
    private $availableValues;
23
    /** @var bool */
24
    private $validateKeys;
25
    /** @var array */
26
    private $errors;
27
    /** @var array */
28
    private $validData;
29
30
    /**
31
     * RangeValidator constructor.
32
     *
33
     * @param array $availableValues
34
     * @param bool  $validateKeys
35
     */
36
    public function __construct(array $availableValues, bool $validateKeys = false)
37
    {
38
        $this->availableValues = array_values($availableValues);
39
        $this->validateKeys = $validateKeys;
40
    }
41
42
    /**
43
     * Validates data.
44
     *
45
     * @param array $values
46
     * @return bool
47
     */
48
    public function validate(array $values) : bool
49
    {
50
        $data = $this->validateKeys ? array_keys($values) : array_values($values);
51
        $diff = array_diff($data, $this->availableValues);
52
53
        if (!empty($diff)) {
54
            $this->errors[] = sprintf("Some data is out of range: %s", implode(', ', $diff));
55
            return false;
56
        }
57
58
        $this->validData = $values;
59
60
        return true;
61
    }
62
63
    /**
64
     * Retrieve valid data.
65
     *
66
     * @return array
67
     */
68
    public function getValidData() : array
69
    {
70
        return $this->validData;
71
    }
72
73
    /**
74
     * Gets errors from validation.
75
     *
76
     * @return array
77
     */
78
    public function getErrors() : array
79
    {
80
        return $this->errors;
81
    }
82
}
83