Skip to content

Commit

Permalink
Merge pull request #300 from Fredrik82/5.x
Browse files Browse the repository at this point in the history
Named routes within RouteGroups
  • Loading branch information
philipobenito authored Jul 9, 2021
2 parents a47c797 + dee2d41 commit 7271d5e
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
19 changes: 19 additions & 0 deletions docs/5.x/routes.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,25 @@ GET /admin/acme/route2
GET /admin/acme/route3
~~~

### Named Routes

Named routes helps when you want to retrieve a Route by a human friendly label.

~~~php
<?php declare(strict_types=1);

$router = new League\Route\Router;
$request = new Request; // Psr/Http/Message/ServerRequestInterface

$router->group('/admin', function (\League\Route\RouteGroup $route) {
$route->map('GET', '/acme/route1', 'AcmeController::actionOne')->setName('actionOne');
$route->map('GET', '/acme/route2', 'AcmeController::actionTwo')->setName('actionTwo');
});

$route = $router->getNamedRoute('actionOne');
$route->getPath(); // "/admin/acme/route1"
~~~

### Conditions

As mentioned above, route conditions can be applied to a group and will be matched across all routes contained in that group, specific routes within the group can override this functionality as displayed below.
Expand Down
11 changes: 11 additions & 0 deletions src/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ public function dispatch(ServerRequestInterface $request): ResponseInterface

public function getNamedRoute(string $name): Route
{
if (!$this->routesPrepared) {
$this->collectGroupRoutes();
}

$this->buildNameIndex();

if (isset($this->namedRoutes[$name])) {
Expand Down Expand Up @@ -222,6 +226,13 @@ protected function buildOptionsRoutes(array $options): void
}
}

protected function collectGroupRoutes(): void
{
foreach ($this->groups as $key => $group) {
$group();
}
}

protected function processGroups(ServerRequestInterface $request): void
{
$activePath = $request->getUri()->getPath();
Expand Down
18 changes: 18 additions & 0 deletions tests/RouteGroupTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,22 @@ public function testGroupAddsStrategyToRoute(): void

$group();
}

public function testGroupWithNamedRoutes(): void
{
$router = new Router();
$name = 'route';
$expected = null;

$router->group('/acme', function (RouteGroup $group) use ($name, &$expected) {
$expected = $group->get('/route', function () {
})
->setName($name);
});

$actual = $router->getNamedRoute($name);

$this->assertNotNull($actual);
$this->assertSame($expected, $actual);
}
}

0 comments on commit 7271d5e

Please sign in to comment.