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

/**
 * flCacheOutput Class
 *
 * Class to capture output from a script and store it in the cache.
 *
 * @package fusionLib
 */
class flCacheOutput {
	/**
	 * Array holding id and cache information for nested calls.
	 *
	 * @var array
	 */
	static private $cacheStack = array();

	/**
	 * Begin the output caching or output a cached copy of the data if it's available.
	 *
	 * @param flCache The cache object to use.
	 * @param string $id The id of the cache item.
	 * @return bool false if a cached copy was output or true if a new output should be created.
	 */
	static function begin($cache, $id) {
		// If cache hit then output the results
		if(($data = $cache->get($id)) !== false) {
			echo $data;
			return false;
		}
		// Else start output buffering and return false
		else {
			self::$cacheStack[] = array($cache, $id);
			ob_start();
			ob_implicit_flush(false);
			return true;
		}
	}

	/**
	 * End the current output buffering and store the results in the cache as well
	 * as sending to the browse.
	 *
	 * @param int $lifetime The lifetime of the object in seconds, null to use the default or 0 to never expire.
	 */
	static function end($lifetime = null) {
		// Get the buffer, send to browser & store
		$data = ob_get_flush();
		$c = array_pop(self::$cacheStack);
		$c[0]->store($c[1], $data, $lifetime);
	}
}
