Skip to content

Commit 2db4a5e

Browse files
committed
Add support for routing placeholders to scoped middleware.
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.
1 parent 7b75286 commit 2db4a5e

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

src/Routing/RouteCollection.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,10 @@ public function enableMiddleware($path, array $middleware)
425425
throw new RuntimeException($message);
426426
}
427427
}
428+
// Matches route element pattern in Cake\Routing\Route
429+
$path = '#^' . preg_quote($path, '#') . '#';
430+
$path = preg_replace('/\\\\:([a-z0-9-_]+(?<![-_]))/i', '[^/]+', $path);
431+
428432
if (!isset($this->_middlewarePaths[$path])) {
429433
$this->_middlewarePaths[$path] = [];
430434
}
@@ -447,8 +451,8 @@ public function enableMiddleware($path, array $middleware)
447451
public function getMatchingMiddleware($needle)
448452
{
449453
$matching = [];
450-
foreach ($this->_middlewarePaths as $path => $middleware) {
451-
if (strpos($needle, $path) === 0) {
454+
foreach ($this->_middlewarePaths as $pattern => $middleware) {
455+
if (preg_match($pattern, $needle)) {
452456
$matching = array_merge($matching, $middleware);
453457
}
454458
}

tests/TestCase/Routing/RouteCollectionTest.php

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -747,13 +747,18 @@ public function testEnableMiddlewareWithPlaceholder()
747747
->getMock();
748748
$this->collection->registerMiddleware('callable', $mock);
749749

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

753-
$middleware = $this->collection->getMatchingMiddleware('/articles/123/comments');
752+
$middleware = $this->collection->getMatchingMiddleware('/api-1/articles/comments');
753+
$this->assertEmpty($middleware);
754+
755+
$middleware = $this->collection->getMatchingMiddleware('/api-1/articles/yay/comments');
756+
$this->assertEquals([$mock], $middleware);
757+
758+
$middleware = $this->collection->getMatchingMiddleware('/api-1/articles/123/comments');
754759
$this->assertEquals([$mock], $middleware);
755760

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

0 commit comments

Comments
 (0)