NotFoundMiddleware   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 44
ccs 17
cts 17
cp 1
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A notFound() 0 16 2
A __construct() 0 3 1
A process() 0 6 2
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