<?php

class Eppe_Validate_Db_NoRecordExists extends Zend_Validate_Abstract {
	/**
	 * Error constants
	 */

	const ERROR_RECORD_FOUND = 'recordFound';

	/**
	 * @var array Message templates
	 */
	protected $_messageTemplates = array(
		self::ERROR_RECORD_FOUND => "A record matching '%value%' was found",
	);
	protected $_options;

	public function __construct($options = null) {
		Eppe_Validate::setupConstructorOptions($this, $options);
		$this->_options = $options;
		Eppe_Validate::setupConstructorOptions($this, $options);
	}

	public function isValid($value) {
		$valid = true;
		$this->_setValue($value);

		$sql = $this->_options['column'] . ' LIKE "' . $value . '"';

		if (@$this->_options['exclude_id']) {
			$sql .= ' AND id != ' . $this->_options['exclude_id'];
		}

		$bean = R::findOne($this->_options['bean'], $sql);
		
		if ($bean) {
			$valid = false;
			$this->_error(self::ERROR_RECORD_FOUND);
		}

		return $valid;
	}

}
