Between::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Mbright\Validation\Rule\Sanitize;
4
5
class Between implements SanitizeRuleInterface
6
{
7
    /** @var int */
8
    protected $min;
9
10
    /** @var int */
11
    protected $max;
12
13
    /**
14
     * @param int $min The minimum value.
15
     * @param int $max The maximum value.
16
     */
17 24
    public function __construct(int $min, int $max)
18
    {
19 24
        $this->min = $min;
20 24
        $this->max = $max;
21 24
    }
22
23
    /**
24
     * Check that the value is within the given range.
25
     *
26
     * If the value is greater than the max, assign it to the max. If it is lower than the min, assign it to the min.
27
     *
28
     * @param object $subject The subject to be filtered.
29
     * @param string $field The subject field name.
30
     *
31
     * @return bool True if the value was sanitized, false if not.
32
     */
33 24
    public function __invoke($subject, string $field): bool
34
    {
35 24
        $value = $subject->$field;
36 24
        if (!is_scalar($value)) {
37 3
            return false;
38
        }
39
40 21
        if ($value < $this->min) {
41 6
            $subject->$field = $this->min;
42
        }
43
44 21
        if ($value > $this->max) {
45 6
            $subject->$field = $this->max;
46
        }
47
48
49 21
        return true;
50
    }
51
}
52