<?php
/**
 * Filter chain
 * @author Jérôme Brilland
 * @version 1.0
 * @copyright (c) 2009, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
final class FilterChain {

    /**
     * @var array Filters
     * @access private
     */
    private $filters = array();

    /**
     * @var Controller Controller
     * @access private
     */
    private $controller;

    /**
     * Class constructor
     * @access public
     */
    public function __construct( Controller $controller ) {
        $this->controller = $controller;
    }

    /**
     * Adds a filter
     * @access public
     */
    public function addFilter( IFilter $filter ) {
        $this->filters[] = $filter;
    }

    /**
     * Invokes the next filter in the chain
     * @param Request request Request object
     * @param Response response Response object
     * @access public
     */
    public function execute( Request $request, Response $response ) {
        $filter = array_shift( $this->filters );
        if ( !$filter ) {
            $this->controller->dispatch( $request, $response );
            return;
        }
        $filter->execute( $request, $response, $this );
    }

}

