<?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 - 2013 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flTimer Class
 *
 * Class to provide timer functionality including named timers.
 *
 * @package fusionLib
 */
class flTimer {
	/**
	 * Named timers.
	 *
	 * @var array
	 */
	static private $namedTimers = array();

	/**
	 * The time the timer started.
	 *
	 * @var float
	 */
	private $startTime = 0;

	/**
	 * The current total elapsed time.
	 *
	 * @var float
	 */
	private $elapsed = 0;

	/**
	 * Construct and start the timer.
	 */
	function __construct() {
		$this->start();
	}

	/**
	 * Start the timer.
	 */
	function start() {
		$this->startTime = microtime(true);
		$this->elapsed = 0;
	}

	/**
	 * Stop the timer.
	 *
	 * @return float The elapsed time in seconds or false if timer not running.
	 */
	function stop() {
		if($this->startTime) {
			$this->elapsed += microtime(true) - $this->startTime;
			$this->startTime = 0;
			return $this->elapsed;
		}
		else
			return false;
	}

	/**
	 *	Pause the timer and accumulate the elapsed time.
	 */
	function pause() {
		// If running stop and save elapsed time.
		if($this->startTime) {
			$this->elapsed += microtime(true) - $this->startTime;
			$this->startTime = 0;
		}
	}

	/**
	 * Resume a paused timer.
	 */
	function resume() {
		$this->startTime = microtime(true);
	}

	/**
	 * Reset the timer.
	 */
	function reset() {
		$this->startTime = $this->elapsed = 0;
	}

	/**
	 * Get the time elapsed since the timer started.
	 *
	 * @return float The number of seconds that the timer has run for.
	 */
	function elapsed() {
		return $this->startTime ? $this->elapsed + microtime(true) - $this->startTime : $this->elapsed;
	}

	/**
	 * Get the named timer.
	 *
	 * @param string $name The name of the timer.
	 * @return flTimer The timer object.
	 */
	static function getTimer($name) {
		return isset(self::$namedTimers[$name]) ? self::$namedTimers[$name] : self::$namedTimers[$name] = new flTimer();
	}
}
