Last active
August 29, 2015 14:23
-
-
Save NigelGreenway/336e0793af202eeefcea to your computer and use it in GitHub Desktop.
A quick mock up of generating routes from a Route config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace League\Route\RouteGenerator; | |
final class RouteGenerator | |
{ | |
private $routes; | |
public function __construct( | |
array $routes = [] | |
) { | |
$this->routes = $routes; | |
} | |
public function generateRoute($alias, array $params = []) | |
{ | |
$route = $this->findRoute($alias); | |
$elements = array_map(function($element) use ($params) { | |
foreach ($params as $key => $value) { | |
if (preg_match('#\{'.$key.'\}#', $element, $matches)) { | |
return preg_replace('#\{'.$key.'\}#', $value, $matches[0]); | |
} | |
} | |
return $element; | |
}, explode('/', $route['pattern'])); | |
return sprintf( | |
'%s://%s%s', | |
'http', | |
$_SERVER['HTTP_HOST'], | |
implode('/', $elements) | |
); | |
return filter_var($route, FILTER_VALIDATE_URL); | |
} | |
private function findRoute($alias) | |
{ | |
foreach($this->routes as $modules) { | |
if (array_key_exists($alias, $modules)) { | |
return $modules[$alias]; | |
} | |
} | |
throw new \Exception(sprintf('The route [%s] does not exist. Please check your configuration.', $alias)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment