Советы выше - не универсальны и ведут к дублированию кода.
Вот более правильный универсальный вариант:
class Checker
{
/**
* @var mixed
*/
protected mixed $value;
/**
* @var int
*/
protected int $minimalValue = 0;
/**
* @var array
*/
protected array $excludeValues = [];
/**
* Checker constructor.
* @param mixed $value
*/
public function __construct(mixed $value)
{
return $this->checkValue($value, function() use ($value) {
$this->value = $value;
return $this;
});
}
/**
* @param mixed $value
* @return $this
*/
public function setMinimalValue(mixed $value): self
{
return $this->checkValue($value, function() use ($value) {
$this->minimalValue = $value;
return $this;
});
}
/**
* @param mixed $value
* @return $this
*/
public function setExcludeValue(mixed $value): self
{
return $this->checkValue($value, function() use ($value) {
if (!array_search($value, $this->excludeValues)) {
array_push($this->excludeValues, $value);
}
return $this;
});
}
/**
* @return bool
*/
public function validate(): bool
{
return $this->value > $this->minimalValue && !in_array($this->value, $this->excludeValues);
}
/**
* @param mixed $value
* @param callable $callable
* @return $this
*/
protected function checkValue(mixed $value, callable $callable): self
{
if (!$this->isInteger($value)) {
throw new \RuntimeException("Value `$value` is not integer");
}
return $callable($this);
}
/**
* @param mixed $val
* @return bool
*/
protected function isInteger(mixed $val): bool
{
if (!is_scalar($val) || is_bool($val)) {
return false;
}
return $this->isFloat($val)
? false
: preg_match('~^((?:\+|-)?[0-9]+)$~', $val) === 1;
}
/**
* @param mixed $val
* @return bool
*/
protected function isFloat(mixed $val): bool
{
if (!is_scalar($val) || is_bool($val)) {
return false;
}
$type = gettype($val);
if ($type === "double") {
return true;
} else {
return preg_match("/^([+-]*\\d+)*\\.(\\d+)*$/", $val) === 1;
}
}
}
try {
echo (int) (new Checker('5'))
->setMinimalValue(4)
->setExcludeValue(107)
->setExcludeValue(107)
->setExcludeValue(108)
->validate();
} catch (\Exception $e) {
echo $e->getMessage();
}