<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class extends Kohana's [ORM] class to create defaults for TSM.
 *
 * @package    TSM
 * @subpackage Core
 * @category   ORM
 * @author     Deon George
 * @copyright  (c) 2010 phpTSMadmin Development Team
 * @license    http://dev.osbill.net/license.html
 */
abstract class ORMTSM extends ORM {
	// Suppress ORMs inclusion of <table_name>.*
	protected $_disable_wild_select = TRUE;

	// Enable the formating of columns
	protected $_object_formated  = array();
	protected $_formated = FALSE;
	protected $_formats = array();

	/**
	 * Format fields for display purposes
	 *
	 * @param   string  column name
	 * @return  mixed
	 */
	protected function _format() {
		$format = Validate::factory($this->_object);

		foreach ($this->_formats as $column => $formats)
			$format->filters($column,$formats);

		if ($format->check())
			foreach ($format as $column => $value)
				$this->_object_formated[$column] = $value;

		$this->_formated = TRUE;
	}

	/**
	 * Return a formated columns, as per the model definition
	 */
	public function display($column) {
		// Trigger a load of the record.
		$value = $this->__get($column);

		// If some of our fields need to be formated for display purposes.
		if ($this->_loaded AND ! $this->_formated AND $this->_formats)
			$this->_format();

		if (isset($this->_object_formated[$column]))
			return $this->_object_formated[$column];
		else
			return $value;
	}

	public static function date($date,$format) {
		return date($format,strtotime($date));
	}

	/**
	 * This function will enhance the [Validate::filter], since it always passes
	 * the value as the first argument and sometimes functions need that to not
	 * be the first argument.
	 *
	 * Currently this implements:
	 *   [date()][date-ref]
	 *
	 * [date-ref]: http://www.php.net/date
	 *
	 * This function will throw an exception if called without a function
	 * defined.
	 *
	 * @param mixed $val Value to be processed
	 * @param string $func Name of function to call
	 * @param string $arg Other arguments for the function
	 */
	final public static function _filters($val,$func,$arg) {
		switch ($func) {
			case 'date':
				return date($arg,$val);
			default:
				throw new Exception(sprintf(_('Unknown function: %s (%s,%s)'),$func,$arg,$val));
		}
	}
}
?>
