<?php
class Length
{
public $violations = [];
/**
* Minimum length.
*
* @var int
*/
private $min;
/**
* Maximum length.
*
* @var int
*/
private $max;
/**
* Charset.
*
* @var string
*/
private $charset;
/**
* Length validation rule constructor.
*
* @param int $min
* @param int $max
* @param string $charset
* @throws InvalidArgumentException
* @throws LogicException
*/
public function __construct(
$min = null,
$max = null,
$charset = 'UTF-8'
)
{
if ($min === null && $max === null) {
throw new \InvalidArgumentException('Either option "min" or "max" must be given.');
}
if ($max < $min) {
throw new \LogicException('"Max" option cannot be less that "min".');
}
$this->min = $min;
$this->max = $max;
$this->charset = $charset;
}
/**
* Validates input.
*
* @param mixed $input
*
* @return bool
*/
public function isValid($input = null)
{
if ($input === null || $input === '') {
return false;
}
$input = (string) $input;
if (!$invalidCharset = !@mb_check_encoding($input, $this->charset)) {
$length = mb_strlen($input, $this->charset);
}
if ($invalidCharset) {
$this->violations[] = 'charset';
return false;
}
if ($this->max !== null && $length > $this->max) {
$this->violations[] = 'max';
return false;
}
if ($this->min !== null && $length < $this->min) {
$this->violations[] = 'min';
return false;
}
return true;
}
}
$length = new Length(-100, ['a', 'b', 'c', 185, null]);
$length->isValid(stream_context_create());
echo sprintf('Count fail violations: %d', count($length->violations));
- Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.27, 8.3.0 - 8.3.15, 8.4.1 - 8.4.2
- Count fail violations: 0
preferences:
78.62 ms | 408 KiB | 5 Q