<?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
 */

/**
 * flCacheFunction Class
 *
 * Class to allow the results of a function or method call to be cached.
 *
 * @package fusionLib
 */
class flCacheFunction {
	/**
	 * Call a function caching the output/return.
	 *
	 * If the function outputs data to the browser then that is detected and captured in the cache.
	 *
	 * @param flCache The cache object to use.
	 * @param string $function The name of the function to call, can also be array($object, 'function).
	 * @param array $params The array of parameters to pass to the function.
	 * @param int $lifetime The lifetime of the object in seconds, null to use the default or 0 to never expire.
	 * @return mixed The result of the function or the cached results.
	 */
	static function call($cache, $function, $params = array(), $lifetime = null) {

		// Create the cache id
		$cacheId = (is_array($function) ? get_class($function[0]) . $function[1] : $function) .  serialize($params);

		// Try reading from cache
		if(($data = $cache->get($cacheId)) === false) {
			// Cache miss so call function
			ob_start();
			ob_implicit_flush(false);
			$data[0] = call_user_func_array($function, $params);
			if(ob_get_length())
				$data[1] = ob_get_flush();
			else {
				ob_end_clean();
				$data[1] = false;
			}

			// Store in cache
			$cache->store($cacheId, $data, $lifetime);
		}
		// Cache hit
		else {
			// Write any output
			if($data[1] !== false)
				echo $data[1];
		}

		// Return the function result
		return $data[0];
	}
}
