IntType.php 1.3 KB

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