Skip to content

Instantly share code, notes, and snippets.

@NigelGreenway
Last active August 29, 2015 14:23
Show Gist options
  • Save NigelGreenway/336e0793af202eeefcea to your computer and use it in GitHub Desktop.
Save NigelGreenway/336e0793af202eeefcea to your computer and use it in GitHub Desktop.
A quick mock up of generating routes from a Route config
<?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