routes = $this->loadRoutes(); $this->path = $this->preparePath(); $this->query = $this->prepareQuery(); $this->requestType = $this->getRequestType(); $this->controller = $this->findController(); $this->controllerPath = $this->setRouteFile(); } private function loadRoutes() { // Check if Path exists if (file_exists(BASEPATH . '/App/routes.php')) { require_once( BASEPATH . '/App/routes.php'); } else { require_once(FRAMEWORKPATH . '/defaults/App/routes.php'); } return $routes; } private function preparePath() { $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); //homepage if ($path === '/') { return $path; } // remove empty directory path $path = rtrim($path, '/'); // remove trailing slash //remove anything after and including ampersand $path = preg_replace('/&.+$/', '', $path); return $path; } private function prepareQuery() { $parsedUri = parse_url($_SERVER['REQUEST_URI']); $queryArray = []; if (isset($parsedUri['query'])) { parse_str($parsedUri['query'], $queryArray); } return $queryArray; } private function getRequestType() { // is the requewst a get or post? if (empty($_POST)) { return 'get'; } else { return 'post'; } } private function findController() { // one to one match if (array_key_exists($this->path, $this->routes)) { return $this->routes[$this->path][$this->requestType]; } foreach ($this->routes as $key => $value) { // Check if key contains a curly bracket, if not continue. We already checked above. if (!strpos($key, '{')) continue; // Remove everything after the curly bracket, from key $keyPath = substr($key, 0, strpos($key, '{')); //see if keyPath matches the first characters of $this->path, only the first characters have to match if (strpos($this->path, $keyPath) === 0) { // We have a potential match. Now check if the parameter count is equal $keyParams = explode('/', $key); $pathParams = explode('/', $this->path); $keyParamCount = count($keyParams); $pathParamCount = count($pathParams); if ($keyParamCount === $pathParamCount) { for ($i=0; $i < $pathParamCount; $i++) { if (strpos($keyParams[$i], '{') !== false) { $keyParams[$i] = substr($keyParams[$i], 1, -1); $this->parameters[$keyParams[$i]] = $pathParams[$i]; return $this->routes[$key][$this->requestType]; } } } } } return '404'; } // checks if the file exists, sets file path private function setRouteFile() { $cp = BASEPATH . '/App/controllers/' . $this->controller . '.php'; if (file_exists($cp)) { return $cp; } else { //Check if 404 exits if (file_exists(BASEPATH . '/App/controllers/404.php')) { return BASEPATH . '/App/controllers/404.php'; } else { return FRAMEWORKPATH . '/defaults/App/controllers/404.php'; } } } public function debug() { echo '
'; echo ''; echo ''; echo ''; echo ''; echo ''; echo '
Url Path' . htmlspecialchars($this->path) . '
Controller Path' . htmlspecialchars($this->controllerPath) . '
Parameters
' . print_r($this->parameters, true) . '
Routes
' . print_r($this->routes, true) . '
'; die(); } }