Created
October 7, 2015 09:36
-
-
Save radmen/92200c62b633320b98a8 to your computer and use it in GitHub Desktop.
Lument getCurrentRoute()
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 | |
$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