<?php

/**
 * Response context object carrying server response back to client
 *
 * Holds a view to be sent back to client. Uses backend view processor
 * to prepare output depending on response type, which can be
 * HTML or Ajax response.
 *
 * @version DR1.7
 */
final class ResponseContext {



	private $backend;
	private $stack;
	private static $instance;



	private function __construct() {
		$this->stack = new ArrayObject();
	}



	/**
	 * Returns instance of response object
	 */
	public static function getInstance() {
		if (!self::$instance) {
			self::$instance = new ResponseContext();
		}
		return self::$instance;
	}



	/**
	 * Defines backend for output to be passed thru
	 *
	 * @since DR1.4
	 */
	public function setBackend(ResponseBackend $backend) {
		$this->backend = $backend;
	}



	/**
	 * Clears all prior output
	 */
	public function clear() {
		$this->stack = new ArrayObject();
	}



	public function importStack(ArrayObject $stack) {
		foreach ($stack as $entry) {
			$this->stack[] = $entry;
		}
	}



	public function getStack() {
		return $this->stack;
	}



	public function __call($method, $args) {
		$this->stack[] = array($method, $args);
	}



	public function __get($property) {
		return new ResponseJsHook($property, $this->stack);
	}



	/**
	 * Returns output to be sent to client
	 *
	 * @since DR1.4
	 */
	public function __toString() {
		if (!$this->backend) {
			trigger_error('response backend not configured');
		}
		try {
			return $this->backend->render($this->stack);
		} catch (Exception $e) {
			trigger_error($e->getMessage());
		}
	}



} // class ResponseContext

?>