<?php

/**
 * Goweb Sitemanager 5 Framework
 * 
 * @version    5.0.10
 * @category   Goweb
 * @package    Goweb_Validate
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
 */

/**
 * Goweb_Validate
 */
Goweb::loadClass('Zend_Validate_Abstract');
/**
 * Classe para validar os tamanhos de uma string
 *
 * @version    5.0.10
 * @category   Goweb
 * @package    Goweb_Validate
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
 */
class Goweb_Validate_Length extends Zend_Validate_Abstract {
    /**
     * Validation failure message for not unique value
     *
     */
    const NOT_LENGTH = 'notLength';

    /**
     * Validation failure message template definitions
     *
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_LENGTH => "'%value%' not valid"
    );
    
    protected $_params = array();

    /**
     * Constructor
     *
     * @param  string  $errorMessage
     * @param  array   $params        Paremetros "maxlength", "minlength" ou "absolut"
     */
    public function __construct($errorMessage, $params) {
        foreach (array_keys($this->_messageTemplates) as $key) $this->setMessage($errorMessage, $key);
        $this->_params = $params;
    }

    /**
     * Valida o valor submetido
     *
     * @param  string  $value
     */
    public function isValid($value) {
        if ($value != '') {
            if (!array_key_exists('minlength', $this->_params) &&
                !array_key_exists('maxlength', $this->_params) &&
                !array_key_exists('absolut',   $this->_params)) {
                throw new Goweb_Exception('No "Goweb_Validator_Length" e necess&aacute;rio fornecer o "minlength" ou "maxlength" ou "absolut" como paremetros');
            }

            if (array_key_exists('absolut', $this->_params)) {
                if (strlen($value) != $this->_params['absolut']) {
                    return false;
                }
            } else {
                if (array_key_exists('minlength', $this->_params)) {
                    if (strlen($value) < $this->_params['minlength']) {
                        return false;
                    }                    
                }
                
                if (array_key_exists('maxlength', $this->_params)) {
                    if (strlen($value) > $this->_params['maxlength']) {
                        return false;
                    }                    
                }
            }
        }        
        return true;        
    }

    public function getParams(){
        return $this->_params;
    }
}