<?php

/**
 * User input length validator
 * 
 * Validates user input with minimum and maximum lengths.
 * 
 * It sets an error if the user input is not a string, if
 * it is shorter than a minimum length, or if it is longer
 * than a maximum length.
 * 
 * Minimum (resp maximum) length checking can be bypassed 
 * by setting minimum (resp maximum) length to 0.
 * 
 * Note: This class uses multibyte library if available
 *
 * @version DR1.6
 */
class LengthValidator extends Validator {



	protected $minLength;
	protected $maxLength;
	


	/**
	 * Constructs a LengthValidator instance
	 * 
	 * @param value : the user input to be validated
	 * @param view : the View where any error shall be posted
	 * @param minLength : the minimum acceptable length
	 * @param maxLength : the maximum acceptable length
	 */
	public function __construct($value, IReadableView $view, $minLength = null, $maxLength = null) {
		parent::__construct($value, $view);
		$this->minLength = $minLength;
		$this->maxLength = $maxLength;
	}



	/**
	 * Validates user input wrt minimum and maximum length
	 * 
	 * @return true if user input is a string which size 
	 * is comprized between minLength and maxLength
	 */
	public function valid() {
		// Always check parent validity first
		if (!parent::valid()) {
			return false;
		}
		// Value must be a string
		if (!is_string($this->value)) {
			$this->view->errorMessage(__('This field must be a string'));
			return false;
		}
		// If multibyte encoding function is available, use it
		$len = function_exists('mb_strlen') ? mb_strlen($this->value) : strlen($this->value);

		// Check minimum length
		if ($this->minLength and $len < $this->minLength) {
			$len == 0
				? $this->view->errorMessage(__('This field is required'))
				: $this->view->errorMessage(sprintf(__('This field must be at least %d characters'), $this->minLength));
			return false;
		}

		// Check maximum length
		if ($this->maxLength and $len > $this->maxLength) {
			$this->view->errorMessage(sprintf(__('This field must be no longer than %d characters'), $this->maxLength));
			return false;
		}
		// Entry is valid
		return true;
	}



} // LengthValidator

?>