Falseclock /
service-layer
| 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
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
|
|||
| 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
|
|||
| 76 | throw new ValidationException(self::ERROR_NOT_INTEGER_OR_FLOAT); |
||
| 77 | } |
||
| 78 | |||
| 79 | $this->minimum = $minimum; |
||
| 80 | |||
| 81 | return $this; |
||
| 82 | } |
||
| 83 | } |
||
| 84 |