Skip to content

Instantly share code, notes, and snippets.

@yooouuri
Created February 1, 2016 17:28
Show Gist options
  • Save yooouuri/7eb48a49fa57994d9e56 to your computer and use it in GitHub Desktop.
Save yooouuri/7eb48a49fa57994d9e56 to your computer and use it in GitHub Desktop.
Routing class
<?php
class Route
{
private $routes = array();
public function init()
{
$match = $this->match();
$controller = '\\app\\Controllers\\' . $match['controller'];
// Create new instance
$instance = new $controller;
// Call the method with his parameters
call_user_func_array([ $instance, $match['action'] ], $match['parameters']);
}
public function map($uri, $callback)
{
// Split into controller & action
list($controller, $action) = explode('@', $callback);
// Check if the controller (and action exists)
if (!file_exists('app' . DS . 'Controllers' . DS . $controller . '.php')) {
throw new Exception('File not found.');
}
include_once 'app' . DS . 'Controllers' . DS . $controller . '.php';
if (!class_exists('App\\Controllers\\' . $controller)) {
throw new Exception('Error 1');
}
if (!method_exists('App\\Controllers\\' . $controller, $action))
{
throw new Exception('App\\Controllers\\' . $controller . '::' . $action . ' is not found.');
}
// Check for {parameters}
preg_match_all('/{(.*?)}/', $uri, $parameters);
// Save the routes
$this->routes[] = [ 'controller' => $controller, 'action' => $action, 'parameters' => $parameters[1], 'uri' => $uri ];
}
public function match()
{
$requestUri = explode('/', ltrim($_SERVER['REQUEST_URI'], '/'));
$index = 0;
foreach ($this->routes as $route) {
$j = 0;
$uri = explode('/', ltrim($route['uri'], '/'));
//for ($i = 0; $i < (count($requestUri) - count($route['parameters'])); $i++) {
for ($i = 0; $i < count($requestUri); $i++) {
if (in_array($requestUri[$i], $uri) === true) {
$j++;
unset($requestUri[$i]);
}
}
if ($j == (count($uri) - count($route['parameters']))) {
break;
}
$index++;
}
// Reset the index
$parameters = array_values($requestUri);
// Check if the parameters are less or not equal
if (count($parameters) != count($this->routes[$index]['parameters'])) {
throw new Exception('Wrong amount of parameters given.');
}
$k = 0;
foreach ($parameters as $parameter) {
if (preg_match('/[A-Za-z0-9]/', $parameter) !== false) {
$k++;
continue;
}
break;
}
if ($k != count($parameters)) {
throw new Exception('There are some parameters not alphanumeric.');
}
// Replace the parameters with real values
$this->routes[$index]['parameters'] = $parameters;
return $this->routes[$index];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment