thephpleague / route

Fast PSR-7 based routing and dispatch component including PSR-15 middleware, built on top of FastRoute.
http://route.thephpleague.com
MIT License
651 stars 126 forks source link

Use Whoops with Route #255

Closed Arcesilas closed 5 years ago

Arcesilas commented 5 years ago

Hi,

I'm trying to have Whoops work with Route. I'm using Middlwares\Whoops to (try to) achieve this. He're a very simple non working example (public/index.php):

<?php
use League\Route\Router;
use Narrowspark\HttpEmitter\SapiEmitter;
use Nyholm\Psr7\Response;
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7Server\ServerRequestCreator;
use Middlewares\Whoops;

require __DIR__.'/../vendor/autoload.php';

$factory = new Psr17Factory();
$request = (new ServerRequestCreator(
    $factory, // ServerRequestFactory
    $factory, // UriFactory
    $factory, // UploadedFileFactory
    $factory  // StreamFactory
))->fromGlobals();

$router = new Router();

$router->get('/', function () {
    $response = new Response();
    $response->getBody()->write('Hello world!');
    return $response;
});
$router->middleware(new Whoops());

$response = $router->dispatch($request);

(new SapiEmitter())->emit($response);

When opening http://localhost, Hello world is correctly displayed. When opening http://localhost/foo, I've got this error message in the console (and not in the browser):

PHP Fatal error:  Uncaught League\Route\Http\Exception\NotFoundException: Not Found in /path/to/project/vendor/league/route/src/Dispatcher.php:124
Stack trace:
#0 /path/to/project/vendor/league/route/src/Dispatcher.php(36): League\Route\Dispatcher->setNotFoundDecoratorMiddleware()
#1 /path/to/project/vendor/league/route/src/Router.php(112): League\Route\Dispatcher->dispatchRequest(Object(Nyholm\Psr7\ServerRequest))
#2 /path/to/project/public/index.php(30): League\Route\Router->dispatch(Object(Nyholm\Psr7\ServerRequest))
#3 {main}
  thrown in /path/to/project/vendor/league/route/src/Dispatcher.php on line 124

The middleware is supposed to work with any PSR-15 middleware dispatcher. Is there anything I'm doing wrong?

Arcesilas commented 5 years ago

The middleware is supposed to work with any PSR-15 middleware dispatcher. Is there anything I'm doing wrong?

Yes... and no...

The Middleware\Whoops documentation is not very clear about Whoops\Run instanciation:

Allows to provide a custom Whoops\Run instance. If it's not defined, creates an instance automatically.

Actually, a new instance is created, but no handler is set (for instance, PrettyPageHandler).

To fix the previous example:

$whoops = (new \Whoops\Run())
                ->prependHandler(new \Whoops\Handler\PrettyPageHandler())
                ->register();
$router->middleware(new Whoops($whoops));

This may help someone...