Skip to content

Commit

Permalink
Add standard middleware to handle missing routes
Browse files Browse the repository at this point in the history
Each framework offers a different request handler or middleware to be
used as last item in the middleware pipeline, which is called when no
route has been matched by the router.

This allows us to delegate the formatting of such error to an error
handling middleware, granting more flexibility to people.
  • Loading branch information
lcobucci committed Jun 21, 2019
1 parent d7856d2 commit f244ca4
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/MissingRouteDispatching.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);

namespace Chimera\Routing;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class MissingRouteDispatching implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
throw NoRouteMatched::fromRequest($request);
}
}
19 changes: 19 additions & 0 deletions src/NoRouteMatched.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);

namespace Chimera\Routing;

use Chimera\Exception;
use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;
use function sprintf;

final class NoRouteMatched extends RuntimeException implements Exception
{
private const HTTP_STATUS = 404;

public static function fromRequest(ServerRequestInterface $request): self
{
return new self(sprintf('Cannot %s %s', $request->getMethod(), $request->getUri()), self::HTTP_STATUS);
}
}
36 changes: 36 additions & 0 deletions tests/MissingRouteDispatchingTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);

namespace Chimera\Routing\Tests;

use Chimera\Routing\MissingRouteDispatching;
use Chimera\Routing\NoRouteMatched;
use PHPUnit\Framework\TestCase;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\ServerRequest;

/**
* @coversDefaultClass \Chimera\Routing\MissingRouteDispatching
*/
final class MissingRouteDispatchingTest extends TestCase
{
/**
* @test
*
* @covers ::process
* @covers \Chimera\Routing\NoRouteMatched::fromRequest
*/
public function processShouldThrowAnExceptionWithRequestInformation(): void
{
$middleware = new MissingRouteDispatching();

$this->expectException(NoRouteMatched::class);
$this->expectExceptionCode(404);
$this->expectExceptionMessage('Cannot GET /testing');

$middleware->process(
new ServerRequest([], [], '/testing', 'GET'),
$this->createMock(RequestHandlerInterface::class)
);
}
}

0 comments on commit f244ca4

Please sign in to comment.