IsBetween::min()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 3
nc 2
nop 1
1
<?php
2
/**
3
 * @author    Nurlan Mukhanov <[email protected]>
4
 * @copyright 2022 Nurlan Mukhanov
5
 * @license   https://en.wikipedia.org/wiki/MIT_License MIT License
6
 * @link      https://github.com/Falseclock/service-layer
7
 */
8
9
declare(strict_types=1);
10
11
namespace Falseclock\Service\Validation\Validators;
12
13
use Falseclock\Service\Validation\ValidationException;
14
use Falseclock\Service\Validation\ValidatorImpl;
15
16
class IsBetween extends ValidatorImpl
17
{
18
    public const ERROR_NO_MAX_DEFINED = "No maximum defined";
19
    public const ERROR_NO_MIN_DEFINED = "No minimum defined";
20
    public const ERROR_NOT_INTEGER_OR_FLOAT = "Provided value is not integer or float type";
21
    /** @var int|float */
22
    protected $maximum;
23
    /** @var int|float */
24
    protected $minimum;
25
26
    /**
27
     * @param null $value
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $value is correct as it would always require null to be passed?
Loading history...
28
     * @return bool
29
     * @throws ValidationException
30
     */
31
    public function check($value = null): bool
32
    {
33
        if (is_null($value) && $this->nullable) {
34
            return true;
35
        }
36
37
        if (!isset($this->minimum)) {
38
            throw new ValidationException(self::ERROR_NO_MIN_DEFINED);
39
        }
40
41
        if (!isset($this->maximum)) {
42
            throw new ValidationException(self::ERROR_NO_MAX_DEFINED);
43
        }
44
45
        if (!is_int($value) && !is_float($value)) {
46
            return false;
47
        }
48
49
        return $value >= $this->minimum and $value <= $this->maximum;
50
    }
51
52
    /**
53
     * @param int|float $maximum
54
     * @return $this
55
     * @throws ValidationException
56
     */
57
    public function max($maximum): IsBetween
58
    {
59
        if (!is_float($maximum) && !is_int($maximum)) {
0 ignored issues
show
introduced by
The condition is_int($maximum) is always true.
Loading history...
60
            throw new ValidationException(self::ERROR_NOT_INTEGER_OR_FLOAT);
61
        }
62
63
        $this->maximum = $maximum;
64
65
        return $this;
66
    }
67
68
    /**
69
     * @param int|float $minimum
70
     * @return $this
71
     * @throws ValidationException
72
     */
73
    public function min($minimum): IsBetween
74
    {
75
        if (!is_float($minimum) && !is_int($minimum)) {
0 ignored issues
show
introduced by
The condition is_int($minimum) is always true.
Loading history...
76
            throw new ValidationException(self::ERROR_NOT_INTEGER_OR_FLOAT);
77
        }
78
79
        $this->minimum = $minimum;
80
81
        return $this;
82
    }
83
}
84