Skip to content

Commit

Permalink
Merge pull request #8 from chimeraphp/standardise-missing-route-dispa…
Browse files Browse the repository at this point in the history
…tching

Add standard middleware to handle missing routes
  • Loading branch information
lcobucci authored Jun 21, 2019
2 parents d7856d2 + f244ca4 commit 4492e4a
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 4492e4a

Please sign in to comment.