Skip to content

Instantly share code, notes, and snippets.

@radmen
Created October 7, 2015 09:36
Show Gist options
  • Save radmen/92200c62b633320b98a8 to your computer and use it in GitHub Desktop.
Save radmen/92200c62b633320b98a8 to your computer and use it in GitHub Desktop.
Lument getCurrentRoute()
<?php
$verbs = 'GET|POST|PUT|DELETE|PATCH';
$routeToRegex = function ($string) use ($verbs) {
$string = preg_replace("/^({$verbs})/", '', $string);
$string = preg_replace('/\{\w+\}/', '\w+', $string);
$string = preg_replace('/\{(\w+):(.+?)\}/', '\2', $string);
return '#^'.$string.'$#';
};
$routeToMethod = function ($string) use ($verbs) {
return preg_replace("/^({$verbs}).+$/", '\1', $string);
};
$routes = [];
foreach (\App::getRoutes() as $routeName => $route) {
$regex = $routeToRegex($routeName);
$method = $routeToMethod($routeName);
$routes[$regex] = compact('route', 'method');
}
uksort($routes, function ($a, $b) {
return strlen($b) - strlen($a);
});
$method = \Request::getMethod();
$path = rtrim(\Request::getPathInfo(), '/');
$foundRoute = null;
foreach ($routes as $regex => $details) {
if (true == preg_match($regex, $path) && $method == $details['method']) {
$foundRoute = $details['route'];
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment