Skip to content

Commit

Permalink
Add support for routing placeholders to scoped middleware.
Browse files Browse the repository at this point in the history
This allows scopes that contain routing placeholders to have middleware
attached and function. I've chosen to use the most liberal placeholder
replacement as scope variables don't allow patterns to be set.
  • Loading branch information
markstory committed Apr 25, 2017
1 parent 7b75286 commit 2db4a5e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
8 changes: 6 additions & 2 deletions src/Routing/RouteCollection.php
Expand Up @@ -425,6 +425,10 @@ public function enableMiddleware($path, array $middleware)
throw new RuntimeException($message);
}
}
// Matches route element pattern in Cake\Routing\Route
$path = '#^' . preg_quote($path, '#') . '#';
$path = preg_replace('/\\\\:([a-z0-9-_]+(?<![-_]))/i', '[^/]+', $path);

if (!isset($this->_middlewarePaths[$path])) {
$this->_middlewarePaths[$path] = [];
}
Expand All @@ -447,8 +451,8 @@ public function enableMiddleware($path, array $middleware)
public function getMatchingMiddleware($needle)
{
$matching = [];
foreach ($this->_middlewarePaths as $path => $middleware) {
if (strpos($needle, $path) === 0) {
foreach ($this->_middlewarePaths as $pattern => $middleware) {
if (preg_match($pattern, $needle)) {
$matching = array_merge($matching, $middleware);
}
}
Expand Down
13 changes: 9 additions & 4 deletions tests/TestCase/Routing/RouteCollectionTest.php
Expand Up @@ -747,13 +747,18 @@ public function testEnableMiddlewareWithPlaceholder()
->getMock();
$this->collection->registerMiddleware('callable', $mock);

$this->collection->enableMiddleware('/articles/:article_id/comments', ['callable']);
$this->markTestIncomplete();
$this->collection->enableMiddleware('/api-:version/articles/:article_id/comments', ['callable']);

$middleware = $this->collection->getMatchingMiddleware('/articles/123/comments');
$middleware = $this->collection->getMatchingMiddleware('/api-1/articles/comments');
$this->assertEmpty($middleware);

$middleware = $this->collection->getMatchingMiddleware('/api-1/articles/yay/comments');
$this->assertEquals([$mock], $middleware);

$middleware = $this->collection->getMatchingMiddleware('/api-1/articles/123/comments');
$this->assertEquals([$mock], $middleware);

$middleware = $this->collection->getMatchingMiddleware('/articles/abc-123/comments/99');
$middleware = $this->collection->getMatchingMiddleware('/api-abc123/articles/abc-123/comments/99');
$this->assertEquals([$mock], $middleware);
}

Expand Down

0 comments on commit 2db4a5e

Please sign in to comment.