JasonLewis\EnhancedRouter\Router::group PHP Method

group() public method

Create a route group with shared attributes. Overloading this method allows developers to chain requirements and filters to all routes within the group.
public group ( array $attributes, Closure $callback ) : JasonLewis\EnhancedRouter\RouteGroup
$attributes array
$callback Closure
return JasonLewis\EnhancedRouter\RouteGroup
    public function group(array $attributes, Closure $callback)
    {
        // Clone the original route collection so that we can re-apply this collection
        // as the set of routes. This will allow developers to apply requirements to
        // a group of routes intead of all routes.
        $original = clone $this->routes;
        parent::group($attributes, $callback);
        // We can now get the routes that were added in this group by comparing the
        // keys of the original routes and of the routes we have after the group
        // callback was fired.
        $routes = array_diff_key($this->routes->all(), $original->all());
        // With a brand new route collection we'll spin through all of the routes
        // defined within our group and add them to the collection.
        $collection = new RouteCollection();
        foreach ($routes as $key => $route) {
            $collection->add($key, $route);
        }
        // Reset the routes on the router to the original collection of routes that
        // we cloned earlier. This way we don't end up with any double ups when
        // the groups are merged later on.
        // $this->routes = $original;
        return $this->routeGroups[] = new RouteGroup($collection, count($this->groupStack));
    }

Usage Example

 public function testOrderOfRoutesIsMaintainted()
 {
     $router = new Router();
     $router->group(array('prefix' => 'foo'), function () use($router) {
         $router->get('bar', function () {
         });
     });
     $router->get('baz', function () {
     });
     $routes = array_keys($router->getRoutes()->all());
     $this->assertEquals(array('get foo/bar', 'get baz'), $routes);
 }