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

RangeValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 0
dl 0
loc 64
ccs 0
cts 24
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A validate() 0 14 3
A getValidData() 0 4 1
A getErrors() 0 4 1
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