Completed
Pull Request — master (#148)
by Alejandro
04:22
created

NotFoundHandler::handle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 1
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Core\Response;
5
6
use Fig\Http\Message\StatusCodeInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use Zend\Diactoros\Response;
11
use Zend\Expressive\Template\TemplateRendererInterface;
12
13
class NotFoundHandler implements RequestHandlerInterface
14
{
15
    public const NOT_FOUND_TEMPLATE = 'notFoundTemplate';
16
17
    /**
18
     * @var TemplateRendererInterface
19
     */
20
    private $renderer;
21
    /**
22
     * @var string
23
     */
24
    private $defaultTemplate;
25
26 4
    public function __construct(TemplateRendererInterface $renderer, string $defaultTemplate = 'ShlinkCore::error/404')
27
    {
28 4
        $this->renderer = $renderer;
29 4
        $this->defaultTemplate = $defaultTemplate;
30 4
    }
31
32
    /**
33
     * Dispatch the next available middleware and return the response.
34
     *
35
     * @param ServerRequestInterface $request
36
     *
37
     * @return ResponseInterface
38
     * @throws \InvalidArgumentException
39
     */
40 4
    public function handle(ServerRequestInterface $request): ResponseInterface
41
    {
42 4
        $accepts = \explode(',', $request->getHeaderLine('Accept'));
43 4
        $accept = \array_shift($accepts);
44 4
        $status = StatusCodeInterface::STATUS_NOT_FOUND;
45
46
        // If the first accepted type is json, return a json response
47 4
        if (\in_array($accept, ['application/json', 'text/json', 'application/x-json'], true)) {
48 3
            return new Response\JsonResponse([
49 3
                'error' => 'NOT_FOUND',
50
                'message' => 'Not found',
51 3
            ], $status);
52
        }
53
54 1
        $notFoundTemplate = $request->getAttribute(self::NOT_FOUND_TEMPLATE, $this->defaultTemplate);
55 1
        return new Response\HtmlResponse($this->renderer->render($notFoundTemplate, ['request' => $request]), $status);
56
    }
57
}
58