Browse Source

Scopes should inherit middleware in their parents

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.
Mark Story 8 years ago
parent
commit
be79ffed26
2 changed files with 20 additions and 1 deletions
  1. 5 0
      src/Routing/RouteBuilder.php
  2. 15 1
      tests/TestCase/Routing/RouteBuilderTest.php

+ 5 - 0
src/Routing/RouteBuilder.php

@@ -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.
@@ -137,6 +138,9 @@ class RouteBuilder
         if (isset($options['namePrefix'])) {
             $this->_namePrefix = $options['namePrefix'];
         }
+        if (isset($options['middleware'])) {
+            $this->middleware = (array)$options['middleware'];
+        }
     }
 
     /**
@@ -885,6 +889,7 @@ class RouteBuilder
             'routeClass' => $this->_routeClass,
             'extensions' => $this->_extensions,
             'namePrefix' => $namePrefix,
+            'middleware' => $this->middleware,
         ]);
         $callback($builder);
     }

+ 15 - 1
tests/TestCase/Routing/RouteBuilderTest.php

@@ -784,9 +784,23 @@ class RouteBuilderTest extends TestCase
             $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());
         });