|
| 1 | +<?php |
| 2 | +declare(strict_types = 1); |
| 3 | + |
| 4 | +namespace C0ntax\ParsleyBundle\Directive\Field\Constraint; |
| 5 | + |
| 6 | +/** |
| 7 | + * Class Range |
| 8 | + * |
| 9 | + * @package C0ntax\ParsleyBundle\Directive\Field\Constraint |
| 10 | + */ |
| 11 | +class Range extends AbstractConstraint |
| 12 | +{ |
| 13 | + /** @var int|float|\DateTime|\DateTimeImmutable */ |
| 14 | + private $min; |
| 15 | + |
| 16 | + /** @var int|float|\DateTime|\DateTimeImmutable */ |
| 17 | + private $max; |
| 18 | + |
| 19 | + /** |
| 20 | + * Range constructor. |
| 21 | + * |
| 22 | + * @param int|float|\DateTime|\DateTimeImmutable $min |
| 23 | + * @param int|float|\DateTime|\DateTimeImmutable $max |
| 24 | + * @param null|string $errorMessageString |
| 25 | + * @throws \InvalidArgumentException |
| 26 | + */ |
| 27 | + public function __construct($min, $max, ?string $errorMessageString = null) |
| 28 | + { |
| 29 | + $this->setMin($min); |
| 30 | + $this->setMax($max); |
| 31 | + parent::__construct($errorMessageString); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * @return string |
| 36 | + */ |
| 37 | + public static function getConstraintId(): string |
| 38 | + { |
| 39 | + return 'range'; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @return array |
| 44 | + */ |
| 45 | + public function getViewAttr(): array |
| 46 | + { |
| 47 | + $minValue = $this->createStringValue($this->getMin()); |
| 48 | + $maxValue = $this->createStringValue($this->getMax()); |
| 49 | + |
| 50 | + return $this->getMergedViewAttr('["'.$minValue.'", "'.$maxValue.'"]'); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @param $value |
| 55 | + * @return string |
| 56 | + */ |
| 57 | + private function createStringValue($value): string |
| 58 | + { |
| 59 | + if ($value instanceof \DateTime || $value instanceof \DateTimeImmutable) { |
| 60 | + return $value->format('Y-m-d H:i:s'); |
| 61 | + } else { |
| 62 | + return (string) $value; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * @return \DateTime|\DateTimeImmutable|float|int |
| 68 | + */ |
| 69 | + private function getMin() |
| 70 | + { |
| 71 | + return $this->min; |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * @param \DateTime|\DateTimeImmutable|float|int $min |
| 76 | + * @return Range |
| 77 | + */ |
| 78 | + private function setMin($min): Range |
| 79 | + { |
| 80 | + $this->min = $min; |
| 81 | + |
| 82 | + return $this; |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * @return \DateTime|\DateTimeImmutable|float|int |
| 87 | + */ |
| 88 | + private function getMax() |
| 89 | + { |
| 90 | + return $this->max; |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * @param \DateTime|\DateTimeImmutable|float|int $max |
| 95 | + * @return Range |
| 96 | + */ |
| 97 | + private function setMax($max): Range |
| 98 | + { |
| 99 | + $this->max = $max; |
| 100 | + |
| 101 | + return $this; |
| 102 | + } |
| 103 | +} |
0 commit comments