Skip to content

Instantly share code, notes, and snippets.

@geekish
Created January 18, 2017 17:37
Show Gist options
  • Save geekish/6bd78f379ac9330997b4def0f4dff276 to your computer and use it in GitHub Desktop.
Save geekish/6bd78f379ac9330997b4def0f4dff276 to your computer and use it in GitHub Desktop.
Slim routes
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
$app = new App;
/**
* Prints json representation of routes your Slim app has
* I just add it as a route, could also be useful as a console command
*/
$app->get("/routes", function (Request $request, Response $response) {
$routes = [];
foreach ($this->get("router")->getRoutes() as $id => $route) {
// For PHP < 7.0 (Null coalesce operator '??' is 7.0+)
// $name = is_null($route->getName()) ? $route->getIdentifier() : $route->getName();
$name = $route->getName() ?? $route->getIdentifier();
$pattern = $route->getPattern();
$methods = implode("|", $route->getMethods());
$string = sprintf("%s %s", $methods, $pattern);
if (strpos($name, '.') !== false) {
list($group, $name) = explode('.', $route->getName());
$routes[$group][$name] = $string;
continue;
}
$routes[$name] = $string;
}
$body = json_encode($routes, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$response->getBody()->write($body);
return $response->withHeader("Content-Type", "application/json");
})->setName("test.routes");
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment