Source of file LengthRule.php
Size: 2,902 Bytes - Last Modified: 2017-11-08T13:54:24+00:00
/home/travis/build/bluzphp/framework/src/Validator/Rule/LengthRule.php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 | <?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Validator\Rule; use Bluz\Validator\Exception\ComponentException; use Countable; /** * Check for length in range between minimum and maximum values * * @package Bluz\Validator\Rule */ class LengthRule extends AbstractCompareRule { /** * @var integer minimum value */ protected $minValue; /** * @var integer maximum value */ protected $maxValue; /** * @var bool */ protected $inclusive = true; /** * Setup validation rule * * @param integer|null $min * @param integer|null $max * * @throws \Bluz\Validator\Exception\ComponentException */ public function __construct($min = null, $max = null) { $this->minValue = $min; $this->maxValue = $max; if (!is_numeric($min) && !is_null($min)) { throw new ComponentException( __('"%s" is not a valid numeric length', $min) ); } if (!is_numeric($max) && !is_null($max)) { throw new ComponentException( __('"%s" is not a valid numeric length', $max) ); } if (!is_null($min) && !is_null($max) && $min > $max) { throw new ComponentException( __('"%s" cannot be less than "%s" for validation', $min, $max) ); } } /** * Check input data * * @param string $input * * @return bool */ public function validate($input): bool { if (!$length = $this->extractLength($input)) { return false; } return (is_null($this->minValue) || $this->less($this->minValue, $length)) && (is_null($this->maxValue) || $this->less($length, $this->maxValue)); } /** * Extract length * * @param string|object $input * * @return integer|false */ protected function extractLength($input) { if (is_string($input)) { return mb_strlen($input, mb_detect_encoding($input)); } elseif (is_array($input) || $input instanceof Countable) { return count($input); } elseif (is_object($input)) { return count(get_object_vars($input)); } return false; } /** * Get error template * * @return string */ public function getDescription() : string { if (!$this->minValue) { return __('must have a length lower than "%d"', $this->maxValue); } if (!$this->maxValue) { return __('must have a length greater than "%d"', $this->minValue); } return __('must have a length between "%d" and "%d"', $this->minValue, $this->maxValue); } } |