* @template-implements TInternalValueValidator */ class IntegerValidator extends BasedValidator { use TIdenticalValidDefaultValidator; use TInternalValueValidator; /** * @var string The locale thousands separator */ private string $thousandsSeparator; /** * @var int|null The minimal value allowed, Null if none */ private ?int $minAllowedValue = null; /** * @var int|null The maximal value allowed, Null if none */ private ?int $maxAllowedValue = null; /** * Create a validator * * @param int|null $minAllowedValue The minimal value allowed, Null if none * @param int|null $maxAllowedValue The maximal value allowed, Null if none */ public function __construct (?int $minAllowedValue, ?int $maxAllowedValue) { $locale = localeconv(); $this->thousandsSeparator = preg_quote($locale['thousands_sep'], '/'); $this->setMinAllowedValue($minAllowedValue); $this->setMaxAllowedValue($maxAllowedValue); $this->value = 0; parent::__construct( new RegexValidator( /** @lang PhpRegExp */ '/^[+-]?(?:\d{1,3}' . $this->thousandsSeparator . '?(?:\d{3}' . $this->thousandsSeparator . '?)*\d{3}|\d{1,3})$/' ) ); } /** * @inheritDoc */ public function validate (mixed $value): bool { if (!parent::validate($value)) { return false; } $this->setValue( (int)preg_replace( [ '/^\+/', '/' . $this->thousandsSeparator . '/', ], [ '', '', ], $value ) ); if ($this->getMinAllowedValue() !== null && $value < $this->getMinAllowedValue()) { return false; } if ($this->getMaxAllowedValue() !== null && $value > $this->getMaxAllowedValue()) { return false; } return true; } /** * The minimal value allowed, Null if none * * @return int|null The minimal value allowed, Null if none */ public function getMinAllowedValue (): ?int { return $this->minAllowedValue; } /** * Set the minimal value allowed * * @param int|null $minAllowedValue The minimal value allowed, Null if none * * @return $this */ public function setMinAllowedValue (?int $minAllowedValue): self { if ($minAllowedValue !== null && $this->getMaxAllowedValue() !== null && $minAllowedValue > $this->getMaxAllowedValue()) { throw new InvalidArgumentException('The minimal allowed value must be null or lesser than the maximal allowed value'); } $this->minAllowedValue = $minAllowedValue; return $this; } /** * The maximal value allowed, Null if none * * @return int|null The maximal value allowed, Null if none */ public function getMaxAllowedValue (): ?int { return $this->maxAllowedValue; } /** * Set the maximal value allowed * * @param int|null $maxAllowedValue The maximal value allowed, Null if none * * @return $this */ public function setMaxAllowedValue (?int $maxAllowedValue): self { if ($maxAllowedValue !== null && $this->getMinAllowedValue() !== null && $maxAllowedValue < $this->getMinAllowedValue()) { throw new InvalidArgumentException('The maximal allowed value must be null or greater than the minimal allowed value'); } $this->maxAllowedValue = $maxAllowedValue; return $this; } }