Skip to content

Commit

Permalink
Fixed root routes
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiopvilar committed Aug 2, 2015
1 parent 2f064f0 commit 5d90882
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/router.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,27 @@ public static function delete($route, $callback){
class RouteImplementation {

private $routes = [];
private $root = false;
private $base = '';

public function __construct(){
$this->base = get_bloginfo('url');
add_filter('generate_rewrite_rules', [$this, 'rewrite_url']);
add_filter('query_vars', [$this, 'query_vars']);
add_filter('init', [$this, 'flush_rewrite_rules']);
add_action("parse_request", [$this, 'parse_request']);
}

public function __destruct() {
$url = "http" . (($_SERVER['SERVER_PORT'] == 443) ? "s://" : "://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if($this->root && str_replace($this->base, '', $url) == '/'){
$route = $this->getRoute($this->root);
$this->getCallback($route, []);
Ampersand::getInstance()->run();
exit(0);
}
}

private function addRoute($method, $route, $callback) {

$robj = [];
Expand All @@ -53,10 +66,17 @@ private function addRoute($method, $route, $callback) {

// Generate the regex url
$broken = array_values(array_filter(explode('/', $route)));

if(count($broken) == 1) {
$robj['regex'] = ''.$broken[0].'/?';
$robj['qstring'] = 'index.php?amp_route='.$robj['id'];
$robj['params'] = [];

} elseif (count($broken) == 0) {
$this->root = $robj['id'];
$robj['regex'] = false;
$robj['qstring'] = false;
$robj['params'] = [];
} else {

$robj['regex'] = '';
Expand Down Expand Up @@ -123,7 +143,7 @@ public function flush_rewrite_rules() {
$rules = $GLOBALS['wp_rewrite']->wp_rewrite_rules();
$need = false;
foreach($this->routes as $route) {
if (!isset( $rules[$route['regex']])) $need = true;
if ($route['regex'] && !isset( $rules[$route['regex']])) $need = true;
}

if($need){
Expand All @@ -137,7 +157,7 @@ public function rewrite_url( $wp_rewrite ) {
$new_rules = [];

foreach($this->routes as $route) {
$new_rules[$route['regex']] = $route['qstring'];
if($route['regex']) $new_rules[$route['regex']] = $route['qstring'];
}

$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
Expand All @@ -161,6 +181,7 @@ public function parse_request($wp_query) {
}
}


public function registerGET($route, $callback) {
$this->addRoute('GET', $route, $callback);
}
Expand Down

0 comments on commit 5d90882

Please sign in to comment.