Skip to content

Commit 4492e4a

Browse files
authored
Merge pull request #8 from chimeraphp/standardise-missing-route-dispatching
Add standard middleware to handle missing routes
2 parents d7856d2 + f244ca4 commit 4492e4a

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

src/MissingRouteDispatching.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace Chimera\Routing;
5+
6+
use Psr\Http\Message\ResponseInterface;
7+
use Psr\Http\Message\ServerRequestInterface;
8+
use Psr\Http\Server\MiddlewareInterface;
9+
use Psr\Http\Server\RequestHandlerInterface;
10+
11+
final class MissingRouteDispatching implements MiddlewareInterface
12+
{
13+
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
14+
{
15+
throw NoRouteMatched::fromRequest($request);
16+
}
17+
}

src/NoRouteMatched.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace Chimera\Routing;
5+
6+
use Chimera\Exception;
7+
use Psr\Http\Message\ServerRequestInterface;
8+
use RuntimeException;
9+
use function sprintf;
10+
11+
final class NoRouteMatched extends RuntimeException implements Exception
12+
{
13+
private const HTTP_STATUS = 404;
14+
15+
public static function fromRequest(ServerRequestInterface $request): self
16+
{
17+
return new self(sprintf('Cannot %s %s', $request->getMethod(), $request->getUri()), self::HTTP_STATUS);
18+
}
19+
}

tests/MissingRouteDispatchingTest.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace Chimera\Routing\Tests;
5+
6+
use Chimera\Routing\MissingRouteDispatching;
7+
use Chimera\Routing\NoRouteMatched;
8+
use PHPUnit\Framework\TestCase;
9+
use Psr\Http\Server\RequestHandlerInterface;
10+
use Zend\Diactoros\ServerRequest;
11+
12+
/**
13+
* @coversDefaultClass \Chimera\Routing\MissingRouteDispatching
14+
*/
15+
final class MissingRouteDispatchingTest extends TestCase
16+
{
17+
/**
18+
* @test
19+
*
20+
* @covers ::process
21+
* @covers \Chimera\Routing\NoRouteMatched::fromRequest
22+
*/
23+
public function processShouldThrowAnExceptionWithRequestInformation(): void
24+
{
25+
$middleware = new MissingRouteDispatching();
26+
27+
$this->expectException(NoRouteMatched::class);
28+
$this->expectExceptionCode(404);
29+
$this->expectExceptionMessage('Cannot GET /testing');
30+
31+
$middleware->process(
32+
new ServerRequest([], [], '/testing', 'GET'),
33+
$this->createMock(RequestHandlerInterface::class)
34+
);
35+
}
36+
}

0 commit comments

Comments
 (0)