<?php

function route( $urls )
{
    $path = str_replace(dirname($_SERVER['PHP_SELF']), '', $_SERVER['REQUEST_URI']);
    $path = ltrim($path, '/');
    
    foreach($urls as $pattern => $app)
    {
        if (preg_match($pattern, $path, $match))
        {

            if (is_array($app))
            {
                if (is_object($app[0]))
                {
                    return call_user_method_array($app[1], $app[0], $match);
                }
                else if (class_exists($app[0]))
                {
                    $obj = new $app[0];
                    return call_user_method_array($app[1], $obj, $match);
                }
            }
            //function call
            else if (function_exists($app))
            {
                return call_user_func($app, $match);
            }
            //simple inclusion
            else if (is_file($app))
            {
                include( $app );
                break;
            }
        }
    }
    
    $htmlpath = htmlentities( $path );
    header('HTTP 404 Not Found');
    echo <<<EOD
<html><head>
        <title>404 Not Found</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head><body>
        <h1>404 Not Found</h1>
        <p>The address $htmlpath is not available. Please check your address</p>
</body></html>
EOD;
    exit;
}

?>
