<?php

/**
 * The <strong>Router</strong> class determines which controller needs to be loaded, 
 * based on the request passed to it.
 *
 * @copyright Trusto Tech 2015-2016
 * @package System\Core
 */
class Router {

    /**
     * The route method takes a request object, and will try to find a route match for the URI contained in the request. 
     * If there is a match, the route method will create a new route otherwise a default route will be created. 
     *
     * @param Request @request Holds the request object
     * @uses Request->getController() To retrieve the controller name
     * @uses Request->getMethod() To retrieve the method name
     * @uses Request->getArgs() To retrieve an array of arguments
     * @return mixed Calls the controller, methods and arguments on success, or displays error message on failure.
     */
    public static function route(Request $request) {
        $controller_name = $request->getController();
        $method_name = $request->getMethod();
        $args = $request->getArgs();
        if (preg_match('/</', $method_name))
            exit();
        if (include_custom_path('Controllers' . DIRECTORY_SEPARATOR . $controller_name . '.php'))
            $controller_name .= 'Custom';
        if (class_exists($controller_name)) {
            $controller_obj = new $controller_name;
            if (!is_callable(array($controller_obj, $method_name)))
                $method_name = is_callable(array($controller_obj, 'landing')) ? 'landing' : '';
            if (!empty($method_name)) {
                if (!empty($args))
                    call_user_func_array(array($controller_obj, $method_name), $args);
                else
                    call_user_func(array($controller_obj, $method_name));
                return;
            }
        }
        $controller_obj = new error_class;
        $controller_obj->Error404();
    }

}
