<?php

class ViewCachingFilter implements InterceptingFilter {



	protected $cache;
	protected $doLog;
	protected $hit = false;
	protected $hash = '';
	protected $action;
	protected $args;
	protected static $doCache = false;



	public function __construct(Cache_Lite $c, $doLog = false) {
		$this->cache = $c;
		$this->doLog = $doLog;
		$this->args = new ArrayObject();
	}



	public static function buildHash(RequestContext $request) {
		$out = array(md5($request->getAction()));
		foreach ($request->getArgs() as $arg) {
			$out[] = md5($arg);
		}
		return implode('-', $out);
	}



	public static function cache() {
		self::$doCache = true;
	}



	public function preProcess(RequestContext $request, ResponseContext $response) {
		$this->hash = self::buildHash($request);
		$this->action = $request->getAction();
		$this->args = $request->getArgs();
		if ($this->cache->get($this->hash)) {
			$this->hit = true;
			$request->clear();
		}
	}



	public function postProcess(RequestContext $request, ResponseContext $response) {
		if ($this->hit) {
			$request->configure($this->action, $this->args);
			$response->clear();
			$response->importStack(new ArrayObject($this->cache->get($this->hash)));
			$mark = '+';
		} elseif (self::$doCache) {
			$request->configure($this->action, $this->args);
			$this->cache->save((array)$response->getStack(), self::buildHash($request));
			$mark = '-';
		} else {
			$mark = 'X';
		}
		if ($this->doLog) {
			file_put_contents('var/log/caching.log', $mark . "\t" . $request->getAction() . "\n", FILE_APPEND);
		}
	}



} // class ViewCachingFilter

?>