Range   A
last analyzed

Complexity

Total Complexity 19

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 28
c 3
b 1
f 0
dl 0
loc 78
rs 10
wmc 19

2 Methods

Rating   Name   Duplication   Size   Complexity  
B isValid() 0 35 11
B __construct() 0 16 8
1
<?php
2
3
namespace Kontrolio\Rules\Core;
4
5
use DateTime as PhpDateTime;
6
use DateTimeInterface;
7
use InvalidArgumentException;
8
use LogicException;
9
use Kontrolio\Rules\AbstractRule;
10
11
/**
12
 * Range of values validation rule.
13
 *
14
 * @package Kontrolio\Rules\Core
15
 */
16
class Range extends AbstractRule
17
{
18
    /**
19
     * @var mixed|null
20
     */
21
    protected $min;
22
23
    /**
24
     * @var mixed|null
25
     */
26
    protected $max;
27
28
    /**
29
     * Range constructor.
30
     *
31
     * @param mixed $min
32
     * @param mixed $max
33
     */
34
    public function __construct($min = null, $max = null)
35
    {
36
        if ($min === null && $max === null) {
37
            throw new InvalidArgumentException('Either option "min" or "max" must be given.');
38
        }
39
40
        if ($min !== null && $max !== null && $min > $max) {
41
            throw new LogicException('"Min" option cannot be greater that "max".');
42
        }
43
44
        if ($max !== null && $max < $min) {
45
            throw new LogicException('"Max" option cannot be less that "min".');
46
        }
47
        
48
        $this->min = $min;
49
        $this->max = $max;
50
    }
51
52
    /**
53
     * Validates input.
54
     *
55
     * @param mixed $input
56
     *
57
     * @return bool
58
     */
59
    public function isValid($input = null)
60
    {
61
        if ($input === null) {
62
            return false;
63
        }
64
65
        if (!is_numeric($input) && !$input instanceof DateTimeInterface) {
66
            $this->violations[] = 'numeric';
67
68
            return false;
69
        }
70
71
        if ($input instanceof DateTimeInterface) {
72
            if (is_string($this->min)) {
73
                $this->min = new PhpDateTime($this->min);
74
            }
75
76
            if (is_string($this->max)) {
77
                $this->max = new PhpDateTime($this->max);
78
            }
79
        }
80
81
        if ($this->max !== null && $input > $this->max) {
82
            $this->violations[] = 'max';
83
84
            return false;
85
        }
86
87
        if ($this->min !== null && $input < $this->min) {
88
            $this->violations[] = 'min';
89
90
            return false;
91
        }
92
93
        return true;
94
    }
95
}
96