FloatType.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace PhpDevCommunity\RequestKit\Type;
  3. use PhpDevCommunity\RequestKit\Type\Traits\StrictTrait;
  4. use PhpDevCommunity\RequestKit\ValidationResult;
  5. use PhpDevCommunity\Validator\Assert\Numeric;
  6. final class FloatType extends AbstractType
  7. {
  8. use StrictTrait;
  9. private ?float $min = null;
  10. private ?float $max = null;
  11. public function min(float $min): self
  12. {
  13. $this->min = $min;
  14. return $this;
  15. }
  16. public function max(float $max): self
  17. {
  18. $this->max = $max;
  19. return $this;
  20. }
  21. protected function validateValue(ValidationResult $result): void
  22. {
  23. if ($this->isStrict() && !is_float($result->getValue())) {
  24. $result->setError("Value must be a float, got: " . gettype($result->getValue()));
  25. return;
  26. }
  27. if ($this->isStrict() === false && is_numeric($result->getValue())) {
  28. $value = floatval($result->getValue());
  29. $result->setValue($value);
  30. }
  31. $validator = new Numeric();
  32. if ($validator->validate($result->getValue()) === false) {
  33. $result->setError($validator->getError());
  34. }
  35. }
  36. }