<?php

class Agro_Plugin_Time extends Zend_Controller_Plugin_Abstract {
	const EVENT_ROUTE_STARTUP = 1;
	const EVENT_ROUTE_SHUTDOWN = 2;
	const EVENT_DISPATCH_LOOP_STARTUP = 3;
	const EVENT_PRE_DISPATCH = 4;
	const EVENT_POST_DISPATCH = 5;
	const EVENT_DISPATCH_LOOP_SHUTDOWN = 6;
	 
	static protected $_startTime = array(
		self::EVENT_ROUTE_STARTUP => null,
		self::EVENT_ROUTE_SHUTDOWN => null,
		self::EVENT_DISPATCH_LOOP_STARTUP => null,
		self::EVENT_PRE_DISPATCH => null,
		self::EVENT_POST_DISPATCH => null,
		self::EVENT_DISPATCH_LOOP_SHUTDOWN => null
	);
 
	public function routeStartup(Zend_Controller_Request_Abstract $request)
	{
    	self::$_startTime[self::EVENT_ROUTE_STARTUP] = $this->_microtime();
	}
 
	public function routeShutdown(Zend_Controller_Request_Abstract $request)
	{
		self::$_startTime[self::EVENT_ROUTE_SHUTDOWN] = $this->_microtime();
	}
 
	public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
	{
		self::$_startTime[self::EVENT_DISPATCH_LOOP_STARTUP] = $this->_microtime();
	}
	
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
		self::$_startTime[self::EVENT_PRE_DISPATCH] = $this->_microtime();
	}

	public function postDispatch(Zend_Controller_Request_Abstract $request)
	{
		self::$_startTime[self::EVENT_POST_DISPATCH] = $this->_microtime();
	}
	
	public function dispatchLoopShutdown()
	{
		self::$_startTime[self::EVENT_DISPATCH_LOOP_SHUTDOWN] = $this->_microtime();
	}
	
 	public function getStartTime($event=null)
	{
		if ($event) {
      		if (!isset(self::$_startTime[$event]))
      		{
				throw new Zend_Exception('Invalid value for $event: '. $event);
			}
			
			return self::$_startTime[$event];
		}
		
		return self::$_startTime;
	}
	
	public function getElapsedTime($event=self::EVENT_ROUTE_STARTUP)
	{
		$startTime = $this->getStartTime($event);
		
		if (!$startTime)
		{
			throw new Zend_Exception('Event has not been initialized yet');
		}
		
		$endTime = $this->_microtime();
		$elapsedTime = $endTime - $startTime;
 
		return $elapsedTime;
	}
	
	private function _microtime()
	{
		if (version_compare(PHP_VERSION, '5.0.0', '>='))
		{
			return microtime(true);
		} else {
			list($usec, $sec) = explode(" ", microtime());
			return ((float)$usec + (float)$sec);
		}
	}
}