Example #1
0
 public static function response()
 {
     // get the path from url
     $request_uri = Request::getParam('uri');
     $function = null;
     // iterate route list
     foreach (static::$list as $uri_pattern_regex => $options) {
         // replace the required route format to regex
         $uri_pattern_regex = preg_replace('/<<(?P<args>.*?)>>/', '(?P<$1>[^/]+)', $uri_pattern_regex);
         // replace the not required route format to regex
         $uri_pattern_regex = preg_replace('/(?P<part>[\\/]<\\?(.*?)\\?>+)/', '/?(?P<$2>[.\\w\\d\\X\\-%/]*)', $uri_pattern_regex);
         // replace '/' character to escaped '\/' for regex
         $uri_pattern_regex = preg_replace('/\\//', '\\/', $uri_pattern_regex);
         // extend it with regex anchors
         $uri_pattern_regex = '/^' . $uri_pattern_regex . '$/';
         $match = preg_match($uri_pattern_regex, $request_uri);
         // IF match the uri_pattern and correct request method from route pattern list
         // THEN store the action and break the loop
         if ($match && ($options['request_method'] == Request::getParam('method') || $options['request_method'] == 'any')) {
             $function = $options['action'];
             break;
         }
     }
     if ($function) {
         // get the action of route parameters
         $function_parameters = static::getArgs($function);
         // search the args of request uri
         preg_match_all($uri_pattern_regex, $request_uri, $request_uri_args_match);
         $args = [];
         foreach ($function_parameters as $function_arg) {
             // class type parameters because dependency injection
             if ($function_arg->getClass()) {
                 $class_name = $function_arg->getClass()->name;
                 $args[] = new $class_name();
                 continue;
             }
             // normal parameters from request uri
             foreach ($request_uri_args_match as $arg_name => $request_arg_value) {
                 if ($arg_name === $function_arg->name) {
                     $args[] = urldecode($request_arg_value[0]);
                 }
             }
         }
         // call the actions with args of request uri
         if (get_class($function) == 'ReflectionMethod') {
             $declaring_class = $function->getDeclaringClass()->name;
             $response = $function->invokeArgs(new $declaring_class(), $args);
         } else {
             $response = $function->invokeArgs($args);
         }
         if (gettype($response) === 'string') {
             $response = new Response($response);
         }
         return $response;
     }
     Response::abort(404);
 }