<?php

/**
 * Goweb Sitemanager 5 Framework
 * 
 * @version    5.0.0
 * @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 campos únicos
 *
 * @version    5.1.4
 * @category   Goweb
 * @package    Goweb_Validate
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @see        http://framework.zend.com/issues/browse/ZF-1851;jsessionid=5C3CB4ED3622E3679A347E2BB1165E15?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
 * @copyright  2010 (c) Goweb (http://www.goweb.pt)
 */


class Goweb_Validate_Unique extends Zend_Validate_Abstract
{
    /**
     * Validation failure message for not unique value
     *
     */
    const NOT_UNIQUE = 'uniqueNotUnique';

    /**
     * Validation failure message template definitions
     *
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_UNIQUE => "'%value%' already exists"
    );
	
    /**
     * Tabela para efectuar a validação
     *
     * @var String
     */
	protected $_table;

	/**
	 * Coluna para efectuar a validação
	 *
	 * @var String
	 */
	protected $_column;

	/**
	 * Valor que está preenchido
	 *
	 * @var String
	 */
	protected $_current;

	/**
	 * Sets default option values for this instance
	 *
	 * @param Goweb_Db_Model $table
	 * @param String $column
	 * @param String $current
	 */
    public function __construct($errorMessage, $params, $current = null){
        if (!$params['model'] instanceof Goweb_Db_Model) {
            throw new Goweb_Exception('O parâmetro "model" não é do tipo "Goweb_Db_Model".');
        }
        foreach (array_keys($this->_messageTemplates) as $key) $this->setMessage($errorMessage, $key);

        $this->_table = $params['model'];
        $this->_column = $params['col'];
        // the primary key of the row being updated
		// without knowing this validating an unchanged value would fail
		$this->_current = $current;
    }

    public function isValid($value){
        $this->_setValue($value);
		
		$db = $this->_table->getAdapter();
		$this->_table->where($this->_table->getTableName() . '.' . $this->_column . ' = ?', $value);
		if (isset($this->_current)) {
			$current = (array) $this->_current;
			$info = $this->_table->info();
			foreach ($info['primary'] as $key => $column) {
				$this->_table->where($this->_table->getTableName() . '.' . $column . ' <> ?', $current[$key - 1]);
			}
		}
		$row = $this->_table->fetchAll();
		if ($row) {
            $this->_error(current($this->_messageTemplates));
			return false;
		}
		return true;
    }
}