<?php
/**
 * Front controller
 * @author Jérôme Brilland
 * @version 2.0
 * @copyright (c) 2009-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
final class FrontController extends Controller {
    
    /**
     * Dispatches the request
     * @param Request $request Request object
     * @param Response $response Response object
     * @access public
     */
    public function dispatch( Request $request, Response $response ) {
        $this->request = $request;
        $this->response = $response;
        IoC::resolve( 'eventmediator' )->trigger( 'before_dispatch', array( 'controller' => $this, 'request' => $this->request, 'response' => $this->response ) );
        try {
            try {
                $this->forward( $this->request->getAttribute( 'controller' ), $this->request->getAttribute( 'action' ) );
            } catch ( Exception $e ) {
                if ( in_array( get_class( $e ), ['UnknownControllerException', 'UnknownActionException'] ) ) {
                    $this->forward( '\\controllers\\ErrorController', '404' );
                } else if ( 'StopException' != get_class( $e ) ) {
                    IoC::resolve( 'logger' )->write( sprintf( '[%s] [%s] [%s] %s', date( 'Y-m-d H:i:s' ), __FILE__, 'error', $e->getMessage() ) );
                    $this->forward( '\\controllers\\ErrorController', '500' );
                }
            }
        } catch ( StopException $e ) {}
        IoC::resolve( 'eventmediator' )->trigger( 'after_dispatch', array( 'controller' => $this, 'request' => $this->request, 'response' => $this->response ) );
        $this->response->printOut();
        exit( 0 );
    }
}

