|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Jasny\SwitchRoute; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
|
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Middleware that gives a 404 or 405 response on a NotFoundException. |
|
15
|
|
|
*/ |
|
16
|
|
|
class NotFoundMiddleware implements MiddlewareInterface |
|
17
|
|
|
{ |
|
18
|
|
|
protected ResponseFactoryInterface $responseFactory; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Class constructor. |
|
22
|
|
|
* |
|
23
|
|
|
* @param ResponseFactoryInterface $responseFactory Used for default not-found response. |
|
24
|
|
|
*/ |
|
25
|
4 |
|
public function __construct(ResponseFactoryInterface $responseFactory) |
|
26
|
|
|
{ |
|
27
|
4 |
|
$this->responseFactory = $responseFactory; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* The default action for when no route matches. |
|
32
|
|
|
*/ |
|
33
|
3 |
|
protected function notFound(ServerRequestInterface $request): ResponseInterface |
|
34
|
|
|
{ |
|
35
|
3 |
|
$allowedMethods = $request->getAttribute('route:allowed_methods', []); |
|
36
|
|
|
|
|
37
|
3 |
|
if ($allowedMethods === []) { |
|
38
|
1 |
|
$response = $this->responseFactory->createResponse(404, 'Not Found') |
|
39
|
1 |
|
->withHeader('Content-Type', 'text/plain'); |
|
40
|
1 |
|
$response->getBody()->write('Not Found'); |
|
41
|
|
|
} else { |
|
42
|
2 |
|
$response = $this->responseFactory->createResponse(405, 'Method Not Allowed') |
|
43
|
2 |
|
->withHeader('Content-Type', 'text/plain') |
|
44
|
2 |
|
->withHeader('Allow', join(', ', $allowedMethods)); |
|
45
|
2 |
|
$response->getBody()->write('Method Not Allowed'); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
3 |
|
return $response; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Process an incoming server request. |
|
53
|
|
|
*/ |
|
54
|
3 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
55
|
|
|
{ |
|
56
|
|
|
try { |
|
57
|
3 |
|
return $handler->handle($request); |
|
58
|
2 |
|
} catch (NotFoundException $exception) { |
|
59
|
2 |
|
return $this->notFound($request); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|