Example #1
0
 /**
  * [Execute description].
  */
 public static function execute()
 {
     $Url = parse_url($_SERVER['REQUEST_URI'])['path'];
     $local = ['::1', '127.0.0.1'];
     if (!filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) || in_array($_SERVER['REMOTE_ADDR'], $local)) {
         $Url = ltrim($Url, '/');
         $Stack = explode('/', $Url);
         array_shift($Stack);
         $Url = '/' . implode('/', $Stack);
     }
     $routes = array();
     $requestMethod = $_SERVER['REQUEST_METHOD'];
     switch ($requestMethod) {
         case 'GET':
             $routes = self::$routesGet;
             break;
         case 'POST':
             $routes = self::$routesPost;
             break;
         case 'PUT':
             $routes = self::$routesPut;
             break;
         case 'DELETE':
             $routes = self::$routesDelete;
             break;
         default:
             break;
     }
     foreach ($routes as $route) {
         $pattern = '@^' . preg_replace('/\\\\{([^}]+)\\}/', '([a-zA-Z0-9\\-\\_.]+)', preg_quote($route['Url'])) . '$@D';
         $matches = array();
         // Replace untuk optional parameter ?{parameter}
         $pattern = str_replace("\\?([a-zA-Z0-9\\-\\_.]+)", "([a-zA-Z0-9\\-\\_.]+)?", $pattern);
         if ($requestMethod == $route['Method'] && preg_match($pattern, $Url, $matches)) {
             preg_match_all("/\\{([^}]+)\\}/", $route['Url'], $paramMatches);
             array_shift($matches);
             $matchesCombine = [];
             for ($i = 0; $i < count($paramMatches[1]); ++$i) {
                 $matchesCombine[$paramMatches[1][$i]] = isset($matches[$i]) ? $matches[$i] : '';
             }
             $valid = 1;
             foreach ($matchesCombine as $key => $value) {
                 $regex = explode(':', $key);
                 if (isset($regex[1])) {
                     if (!preg_match('~^' . $regex[1] . '$~i', $value)) {
                         $valid = 0;
                     }
                 }
                 if ($regex[0] == 'Pattern') {
                     $key = array_search($value, $matches);
                     unset($matches[$key]);
                 }
             }
             if ($valid == 1) {
                 self::before();
                 $className = 'App\\Controllers\\' . $route['Properties']['Controller'];
                 $functionName = $route['Properties']['Action'];
                 $cls = new $className();
                 Request::$controller = $cls;
                 Request::$function = $functionName;
                 Request::$parameters = $matches;
                 Request::$middleware = $route['Properties']['Middleware'];
                 self::middleware();
                 self::after();
                 return;
             }
         }
     }
     echo '<h1>404 Not Found</h1>';
     echo 'The page that you have requested could not be found.';
     return;
 }