Commit 794b3c28 authored by Fabien Potencier's avatar Fabien Potencier

renamed middleware() to before()

parent 68a5e322
...@@ -3,6 +3,8 @@ Changelog ...@@ -3,6 +3,8 @@ Changelog
This changelog references all backward incompatibilities as we introduce them: This changelog references all backward incompatibilities as we introduce them:
* **2012-06-13**: Renamed ``middleware`` to ``before``
* **2012-06-13**: Added an extension for the Symfony Security component * **2012-06-13**: Added an extension for the Symfony Security component
* **2012-05-31**: Made the ``BrowserKit``, ``CssSelector``, ``DomCrawler``, * **2012-05-31**: Made the ``BrowserKit``, ``CssSelector``, ``DomCrawler``,
......
...@@ -440,33 +440,33 @@ This can be used for a lot of use cases; for instance, here is a simple ...@@ -440,33 +440,33 @@ This can be used for a lot of use cases; for instance, here is a simple
$app->get('/user/subscribe', function () { $app->get('/user/subscribe', function () {
... ...
}) })
->middleware($mustBeAnonymous); ->before($mustBeAnonymous);
$app->get('/user/login', function () { $app->get('/user/login', function () {
... ...
}) })
->middleware($mustBeAnonymous); ->before($mustBeAnonymous);
$app->get('/user/my-profile', function () { $app->get('/user/my-profile', function () {
... ...
}) })
->middleware($mustBeLogged); ->before($mustBeLogged);
The ``middleware`` function can be called several times for a given route, in The ``before`` function can be called several times for a given route, in
which case they are triggered in the same order as you added them to the which case they are triggered in the same order as you added them to the
route. route.
For convenience, the route middlewares functions are triggered with the For convenience, the route before middlewares functions are triggered with the
current ``Request`` instance as their only argument. current ``Request`` instance as their only argument.
If any of the route middlewares returns a Symfony HTTP Response, it will If any of the route before middlewares returns a Symfony HTTP Response, it
short-circuit the whole rendering: the next middlewares won't be run, neither will short-circuit the whole rendering: the next middlewares won't be run,
the route callback. You can also redirect to another page by returning a neither the route callback. You can also redirect to another page by returning
redirect response, which you can create by calling the Application a redirect response, which you can create by calling the Application
``redirect`` method. ``redirect`` method.
If a route middleware does not return a Symfony HTTP Response or ``null``, a If a route before middleware does not return a Symfony HTTP Response or
``RuntimeException`` is thrown. ``null``, a ``RuntimeException`` is thrown.
Global Configuration Global Configuration
-------------------- --------------------
...@@ -481,7 +481,7 @@ middleware, a requirement, or a default value), you can configure it on ...@@ -481,7 +481,7 @@ middleware, a requirement, or a default value), you can configure it on
->requireHttps() ->requireHttps()
->method('get') ->method('get')
->convert('id', function () { // ... }) ->convert('id', function () { // ... })
->middleware(function () { // ... }) ->before(function () { // ... })
; ;
These settings are applied to already registered controllers and they become These settings are applied to already registered controllers and they become
...@@ -652,7 +652,7 @@ would secure all controllers for the backend collection:: ...@@ -652,7 +652,7 @@ would secure all controllers for the backend collection::
$backend = new ControllerCollection(); $backend = new ControllerCollection();
// ensure that all controllers require logged-in users // ensure that all controllers require logged-in users
$backend->middleware($mustBeLogged); $backend->before($mustBeLogged);
.. tip:: .. tip::
......
...@@ -112,21 +112,21 @@ class Application extends \Pimple implements HttpKernelInterface, EventSubscribe ...@@ -112,21 +112,21 @@ class Application extends \Pimple implements HttpKernelInterface, EventSubscribe
return new RedirectableUrlMatcher($app['routes'], $app['request_context']); return new RedirectableUrlMatcher($app['routes'], $app['request_context']);
}); });
$this['route_middlewares_trigger'] = $this->protect(function (KernelEvent $event) use ($app) { $this['route_before_middlewares_trigger'] = $this->protect(function (KernelEvent $event) use ($app) {
$request = $event->getRequest(); $request = $event->getRequest();
$routeName = $request->attributes->get('_route'); $routeName = $request->attributes->get('_route');
if (!$route = $app['routes']->get($routeName)) { if (!$route = $app['routes']->get($routeName)) {
return; return;
} }
foreach ((array) $route->getOption('_middlewares') as $callback) { foreach ((array) $route->getOption('_before_middlewares') as $callback) {
$ret = call_user_func($callback, $request); $ret = call_user_func($callback, $request);
if ($ret instanceof Response) { if ($ret instanceof Response) {
$event->setResponse($ret); $event->setResponse($ret);
return; return;
} elseif (null !== $ret) { } elseif (null !== $ret) {
throw new \RuntimeException(sprintf('Middleware for route "%s" returned an invalid response value. Must return null or an instance of Response.', $routeName)); throw new \RuntimeException(sprintf('The before middleware for route "%s" returned an invalid response value. Must return null or an instance of Response.', $routeName));
} }
} }
}); });
...@@ -516,7 +516,7 @@ class Application extends \Pimple implements HttpKernelInterface, EventSubscribe ...@@ -516,7 +516,7 @@ class Application extends \Pimple implements HttpKernelInterface, EventSubscribe
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) { if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$this->beforeDispatched = true; $this->beforeDispatched = true;
$this['dispatcher']->dispatch(SilexEvents::BEFORE, $event); $this['dispatcher']->dispatch(SilexEvents::BEFORE, $event);
$this['route_middlewares_trigger']($event); $this['route_before_middlewares_trigger']($event);
} }
} }
......
...@@ -157,15 +157,14 @@ class Controller ...@@ -157,15 +157,14 @@ class Controller
/** /**
* Sets a callback to handle before triggering the route callback. * Sets a callback to handle before triggering the route callback.
* (a.k.a. "Route Middleware")
* *
* @param mixed $callback A PHP callback to be triggered when the Route is matched, just before the route callback * @param mixed $callback A PHP callback to be triggered when the Route is matched, just before the route callback
* *
* @return Controller $this The current Controller instance * @return Controller $this The current Controller instance
*/ */
public function middleware($callback) public function before($callback)
{ {
$this->route->middleware($callback); $this->route->before($callback);
return $this; return $this;
} }
......
...@@ -219,18 +219,17 @@ class ControllerCollection ...@@ -219,18 +219,17 @@ class ControllerCollection
/** /**
* Sets a callback to handle before triggering the route callback. * Sets a callback to handle before triggering the route callback.
* (a.k.a. "Route Middleware")
* *
* @param mixed $callback A PHP callback to be triggered when the Route is matched, just before the route callback * @param mixed $callback A PHP callback to be triggered when the Route is matched, just before the route callback
* *
* @return ControllerCollection $this The current Controller instance * @return ControllerCollection $this The current Controller instance
*/ */
public function middleware($callback) public function before($callback)
{ {
$this->defaultRoute->middleware($callback); $this->defaultRoute->before($callback);
foreach ($this->controllers as $controller) { foreach ($this->controllers as $controller) {
$controller->middleware($callback); $controller->before($callback);
} }
return $this; return $this;
......
...@@ -107,17 +107,16 @@ class Route extends BaseRoute ...@@ -107,17 +107,16 @@ class Route extends BaseRoute
/** /**
* Sets a callback to handle before triggering the route callback. * Sets a callback to handle before triggering the route callback.
* (a.k.a. "Route Middleware")
* *
* @param mixed $callback A PHP callback to be triggered when the Route is matched, just before the route callback * @param mixed $callback A PHP callback to be triggered when the Route is matched, just before the route callback
* *
* @return Controller $this The current Controller instance * @return Controller $this The current Controller instance
*/ */
public function middleware($callback) public function before($callback)
{ {
$middlewareCallbacks = $this->getOption('_middlewares'); $callbacks = $this->getOption('_before_middlewares');
$middlewareCallbacks[] = $callback; $callbacks[] = $callback;
$this->setOption('_middlewares', $middlewareCallbacks); $this->setOption('_before_middlewares', $callbacks);
return $this; return $this;
} }
......
...@@ -167,7 +167,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase ...@@ -167,7 +167,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('text/html; charset=ISO-8859-1', $response->headers->get('Content-Type')); $this->assertEquals('text/html; charset=ISO-8859-1', $response->headers->get('Content-Type'));
} }
public function testRoutesMiddlewares() public function testRoutesBeforeMiddlewares()
{ {
$app = new Application(); $app = new Application();
...@@ -191,13 +191,13 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase ...@@ -191,13 +191,13 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
return 'hello'; return 'hello';
}) })
->middleware($middleware1) ->before($middleware1)
->middleware($middleware2); ->before($middleware2);
$app->get('/never-reached', function () use (&$middlewareTarget) { $app->get('/never-reached', function () use (&$middlewareTarget) {
throw new \Exception('This route shouldn\'t run!'); throw new \Exception('This route shouldn\'t run!');
}) })
->middleware($middleware3); ->before($middleware3);
$result = $app->handle(Request::create('/reached')); $result = $app->handle(Request::create('/reached'));
...@@ -205,14 +205,14 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase ...@@ -205,14 +205,14 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('hello', $result->getContent()); $this->assertEquals('hello', $result->getContent());
} }
public function testRoutesMiddlewaresWithResponseObject() public function testRoutesBeforeMiddlewaresWithResponseObject()
{ {
$app = new Application(); $app = new Application();
$app->get('/foo', function () { $app->get('/foo', function () {
throw new \Exception('This route shouldn\'t run!'); throw new \Exception('This route shouldn\'t run!');
}) })
->middleware(function () { ->before(function () {
return new Response('foo'); return new Response('foo');
}); });
...@@ -222,14 +222,14 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase ...@@ -222,14 +222,14 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('foo', $result->getContent()); $this->assertEquals('foo', $result->getContent());
} }
public function testRoutesMiddlewaresWithRedirectResponseObject() public function testRoutesBeforeMiddlewaresWithRedirectResponseObject()
{ {
$app = new Application(); $app = new Application();
$app->get('/foo', function () { $app->get('/foo', function () {
throw new \Exception('This route shouldn\'t run!'); throw new \Exception('This route shouldn\'t run!');
}) })
->middleware(function () use ($app) { ->before(function () use ($app) {
return $app->redirect('/bar'); return $app->redirect('/bar');
}); });
...@@ -240,7 +240,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase ...@@ -240,7 +240,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('/bar', $result->getTargetUrl()); $this->assertEquals('/bar', $result->getTargetUrl());
} }
public function testRoutesMiddlewaresTriggeredAfterSilexBeforeFilters() public function testRoutesBeforeMiddlewaresTriggeredAfterSilexBeforeFilters()
{ {
$app = new Application(); $app = new Application();
...@@ -252,7 +252,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase ...@@ -252,7 +252,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$app->get('/foo', function () use (&$middlewareTarget) { $app->get('/foo', function () use (&$middlewareTarget) {
$middlewareTarget[] = 'route_triggered'; $middlewareTarget[] = 'route_triggered';
}) })
->middleware($middleware); ->before($middleware);
$app->before(function () use (&$middlewareTarget) { $app->before(function () use (&$middlewareTarget) {
$middlewareTarget[] = 'before_triggered'; $middlewareTarget[] = 'before_triggered';
...@@ -293,7 +293,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase ...@@ -293,7 +293,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
/** /**
* @expectedException RuntimeException * @expectedException RuntimeException
*/ */
public function testNonResponseAndNonNullReturnFromRouteMiddlewareShouldThrowRuntimeException() public function testNonResponseAndNonNullReturnFromRouteBeforeMiddlewareShouldThrowRuntimeException()
{ {
$app = new Application(); $app = new Application();
...@@ -304,7 +304,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase ...@@ -304,7 +304,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$app->get('/', function () { $app->get('/', function () {
return 'hello'; return 'hello';
}) })
->middleware($middleware); ->before($middleware);
$app->handle(Request::create('/'), HttpKernelInterface::MASTER_REQUEST, false); $app->handle(Request::create('/'), HttpKernelInterface::MASTER_REQUEST, false);
} }
......
...@@ -136,13 +136,13 @@ class ControllerCollectionTest extends \PHPUnit_Framework_TestCase ...@@ -136,13 +136,13 @@ class ControllerCollectionTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('http', $controller->getRoute()->getRequirement('_scheme')); $this->assertEquals('http', $controller->getRoute()->getRequirement('_scheme'));
} }
public function testMiddleware() public function testBefore()
{ {
$controllers = new ControllerCollection(); $controllers = new ControllerCollection();
$controllers->middleware('mid1'); $controllers->before('mid1');
$controller = $controllers->match('/{id}/{name}/{extra}', function () {})->middleware('mid2'); $controller = $controllers->match('/{id}/{name}/{extra}', function () {})->before('mid2');
$controllers->middleware('mid3'); $controllers->before('mid3');
$this->assertEquals(array('mid1', 'mid2', 'mid3'), $controller->getRoute()->getOption('_middlewares')); $this->assertEquals(array('mid1', 'mid2', 'mid3'), $controller->getRoute()->getOption('_before_middlewares'));
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment