StringType.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace PhpDevCommunity\RequestKit\Type;
  3. use PhpDevCommunity\RequestKit\Type\Traits\StrictTrait;
  4. use PhpDevCommunity\RequestKit\ValidationResult;
  5. use PhpDevCommunity\Validator\Assert\StringLength;
  6. final class StringType extends AbstractStringType
  7. {
  8. use StrictTrait;
  9. private array $allowed = [];
  10. private ?int $min = null;
  11. private ?int $max = null;
  12. public function allowed(string ...$allowed): self
  13. {
  14. $this->allowed = $allowed;
  15. return $this;
  16. }
  17. public function length(int $min, ?int $max = null): self
  18. {
  19. $this->min = $min;
  20. $this->max = $max;
  21. return $this;
  22. }
  23. protected function validateValue(ValidationResult $result): void
  24. {
  25. if ($this->isStrict() && !is_string($result->getValue())) {
  26. $result->setError("Value must be a string, got: " . gettype($result->getValue()));
  27. return;
  28. }
  29. if ($this->isStrict() === false && !is_string($result->getValue())) {
  30. if (is_array($result->getValue())) {
  31. $result->setError("Value must be a string, got: array");
  32. return;
  33. }
  34. $value = strval($result->getValue());
  35. $result->setValue($value);
  36. }
  37. if (!empty($this->allowed) && !in_array($result->getValue(), $this->allowed, $this->isStrict())) {
  38. $result->setError("Value is not allowed, allowed values are: " . implode(", ", $this->allowed));
  39. return;
  40. }
  41. $validator = new StringLength();
  42. if ($this->min) {
  43. $validator->min($this->min);
  44. }
  45. if ($this->max) {
  46. $validator->max($this->max);
  47. }
  48. if ($validator->validate($result->getValue()) === false) {
  49. $result->setError($validator->getError());
  50. }
  51. }
  52. }