Skip to content

Commit

Permalink
Scopes should inherit middleware in their parents
Browse files Browse the repository at this point in the history
Nested scopes should inherit the middleware applied in their parent
scope. This allows scopes to have the behavior that would be expected if
you read them top to bottom.
  • Loading branch information
markstory committed Jul 16, 2017
1 parent bd2973a commit be79ffe
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/Routing/RouteBuilder.php
Expand Up @@ -117,6 +117,7 @@ class RouteBuilder
* - `routeClass` - The default route class to use when adding routes.
* - `extensions` - The extensions to connect when adding routes.
* - `namePrefix` - The prefix to prepend to all route names.
* - `middleware` - The names of the middleware routes should have applied.
*
* @param \Cake\Routing\RouteCollection $collection The route collection to append routes into.
* @param string $path The path prefix the scope is for.
Expand All @@ -137,6 +138,9 @@ public function __construct(RouteCollection $collection, $path, array $params =
if (isset($options['namePrefix'])) {
$this->_namePrefix = $options['namePrefix'];
}
if (isset($options['middleware'])) {
$this->middleware = (array)$options['middleware'];
}
}

/**
Expand Down Expand Up @@ -885,6 +889,7 @@ public function scope($path, $params, $callback = null)
'routeClass' => $this->_routeClass,
'extensions' => $this->_extensions,
'namePrefix' => $namePrefix,
'middleware' => $this->middleware,
]);
$callback($builder);
}
Expand Down
16 changes: 15 additions & 1 deletion tests/TestCase/Routing/RouteBuilderTest.php
Expand Up @@ -784,9 +784,23 @@ public function testScope()
$this->assertEquals('/api/v1', $routes->path());
$this->assertEquals(['prefix' => 'api', 'version' => 1], $routes->params());
});
}

$routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
/**
* Test that nested scopes inherit middleware.
*
* @return void
*/
public function testScopeInheritMiddleware()
{
$routes = new RouteBuilder(
$this->collection,
'/api',
['prefix' => 'api'],
['middleware' => ['auth']]
);
$routes->scope('/v1', function ($routes) {
$this->assertAttributeEquals(['auth'], 'middleware', $routes, 'Should inherit middleware');
$this->assertEquals('/api/v1', $routes->path());
$this->assertEquals(['prefix' => 'api'], $routes->params());
});
Expand Down

0 comments on commit be79ffe

Please sign in to comment.