<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2007 - 2014 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flFormValidator Class
 *
 * Base class for form validators.
 *
 * @package fusionLib
 */
abstract class flFormValidator {
	/**
	 * The message to output on validation failure.
	 *
	 * @var string
	 */
	protected $message;

	/**
	 * The element passed to the validate function.
	 *
	 * @var flFormElement
	 */
	protected $elem;

	/**
	 * Additional tags and their values to insert into the message.
	 *
	 * @var array
	 */
	protected $tags = array();

	/**
	 * Construct the validator.
	 *
	 * @param string $message The message to output on validation failure or null if using the default.
	 * @param string $defaultMsg The default message.
	 */
	function __construct($message, $defaultMsg) {
		$this->message = $message === null ? $defaultMsg : $message;
	}

	/**
	 * Replace the tags in the message with values.
	 *
	 * @param array $tags Pairs of tag names and values.
	 * @param string $msg The message to replace the tags in.
	 * @return string The message with the tags replaced.
	 */
	protected function replaceTags($tags, $msg) {
		foreach($tags as $n => $v)
			$msg = str_replace('{' . $n . '}', $v, $msg);
		return $msg;
	}

	/**
	 * Get the validation failure message.
	 *
	 * @return string The failure message.
	 */
	function getMessage() {
		if(is_array($value = $this->elem->getValue()))
			$value = count($value);
		return $this->replaceTags($this->tags, $this->replaceTags(array('label' => $this->elem->getLabel(), 'current' => fusionLib::htmlChars($value)), $this->message));
	}

	/**
	 * Validate the element against the validator.
	 *
	 * @param flFormElement $elem The element to validate.
	 * @return bool true if the element is valid else false.
	 */
	function validate($elem) {
		$this->elem = $elem;
		return false;
	}

	/**
	 * Get the client side rule for validation.
	 *
	 * @return array [0] The string holding the rule information for use with fusionLib.validation.js
	 * [1] true to use ajax or false, if false is returned instead of an array then no client side validation is done
	 */
	function getClientRule() {
		return false;
	}

	/**
	 * Get the message issued on failed validation in a client friendly format.
	 *
	 * @return string The message for failed validation.
	 */
	function getClientMsg() {
		return "msg: '" . str_replace("'", "\'", $this->message) . "'";
	}

	/**
	 * Get the name of the AJAX callback function.
	 *
	 * @return string The function name or null if not needed.
	 */
	function getAJAXCallback() {
		return null;
	}
}
