123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160 |
- <?php
- namespace Cube\Validate;
- class StringLength extends AbstractValidate
- {
- const NO_STRING = 1;
- const TOO_SHORT = 2;
- const TOO_LONG = 3;
- protected $_messages = array(
- self::NO_STRING => "'%s' expects a string, invalid type given.",
- self::TOO_SHORT => "'%s' must contain at least %value% characters.",
- self::TOO_LONG => "'%s' must contain no more than %value% characters.",
- );
-
- private $_min;
-
- private $_max;
-
- public function __construct(array $data = null)
- {
- $this->setMin($data[0])
- ->setMax($data[1]);
- }
-
- public function getMin()
- {
- return $this->_min;
- }
-
- public function setMin($min)
- {
- $this->_min = (integer)$min;
- return $this;
- }
-
- public function getMax()
- {
- return $this->_max;
- }
-
- public function setMax($max)
- {
- $this->_max = (integer)$max;
- return $this;
- }
-
- public function isValid()
- {
- $value = $this->getValue();
- if (empty($value)) {
- return true;
- }
- $min = $this->getMin();
- $max = $this->getMax();
- if (!is_string($value)) {
- $this->setMessage($this->_messages[self::NO_STRING]);
- return false;
- }
- else if (strlen($value) < $min) {
- $this->setMessage($this->_messages[self::TOO_SHORT]);
- $this->setMessage(
- str_replace('%value%', $min, $this->getMessage()));
- return false;
- }
- else if (strlen($value) > $max &&
- $max > $min
- ) {
- $this->setMessage($this->_messages[self::TOO_LONG]);
- $this->setMessage(
- str_replace('%value%', $max, $this->getMessage()));
- return false;
- }
- return true;
- }
- }
|