Passed
Push — master ( ec5386...e56f88 )
by Andrey
53s queued 14s
created

ViewRenderer::renderJson()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 18
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Application\Exception\Renderer;
6
7
use Psr\Http\Message\ResponseFactoryInterface;
0 ignored issues
show
Bug introduced by
The type Psr\Http\Message\ResponseFactoryInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Psr\Http\Message\ResponseInterface;
0 ignored issues
show
Bug introduced by
The type Psr\Http\Message\ResponseInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use Psr\Http\Message\ServerRequestInterface as Request;
0 ignored issues
show
Bug introduced by
The type Psr\Http\Message\ServerRequestInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Spiral\Exceptions\Verbosity;
0 ignored issues
show
Bug introduced by
The type Spiral\Exceptions\Verbosity was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Spiral\Http\ErrorHandler\RendererInterface;
0 ignored issues
show
Bug introduced by
The type Spiral\Http\ErrorHandler\RendererInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Spiral\Http\Header\AcceptHeader;
0 ignored issues
show
Bug introduced by
The type Spiral\Http\Header\AcceptHeader was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Spiral\Views\Exception\ViewException;
0 ignored issues
show
Bug introduced by
The type Spiral\Views\Exception\ViewException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use Spiral\Views\ViewsInterface;
0 ignored issues
show
Bug introduced by
The type Spiral\Views\ViewsInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
16
/**
17
 * This Renderer is to allow exceptions to be rendered as HTTP responses, either in JSON format if the request
18
 * accepts JSON, or as a view if the request accepts HTML.
19
 * This renderer is intended to be used exclusively by the {@see \Spiral\Http\Middleware\ErrorHandlerMiddleware}
20
 * middleware and will only be active if the DEBUG environment variable is set to false.
21
 *
22
 * @link https://spiral.dev/docs/http-errors
23
 */
24
final class ViewRenderer implements RendererInterface
25
{
26
    private const DEFAULT_VIEW = 'exception/error';
27
    private const VIEW_PATTERN = 'exception/%s';
28
29
    public function __construct(
30
        private readonly ViewsInterface $views,
31
        private readonly ResponseFactoryInterface $responseFactory,
32
        private readonly Verbosity $verbosity,
33
    ) {
34
    }
35
36
    public function renderException(Request $request, int $code, \Throwable $exception): ResponseInterface
37
    {
38
        // If request accepts json, we will render as a json response
39
        $acceptItems = AcceptHeader::fromString($request->getHeaderLine('Accept'))->getAll();
40
        if ($acceptItems && $acceptItems[0]->getValue() === 'application/json') {
41
            return $this->renderJson($code, $exception);
42
        }
43
44
        return $this->renderView($code, $exception);
45
    }
46
47
    private function renderJson(int $code, \Throwable $exception): ResponseInterface
48
    {
49
        $response = $this->responseFactory->createResponse($code);
50
51
        $response = $response->withHeader('Content-Type', 'application/json; charset=UTF-8');
52
53
        $payload = [
54
            'status' => $code,
55
            'error' => $exception->getMessage(),
56
        ];
57
58
        if ($this->verbosity->value > Verbosity::BASIC->value) {
59
            $payload['stacktrace'] = $exception->getTraceAsString();
60
        }
61
62
        $response->getBody()->write(\json_encode($payload));
63
64
        return $response;
65
    }
66
67
    private function renderView(int $code, \Throwable $exception): ResponseInterface
68
    {
69
        $response = $this->responseFactory->createResponse($code);
70
71
        try {
72
            // Try to find view for specific exception code
73
            $view = $this->views->get(\sprintf(self::VIEW_PATTERN, $code));
74
        } catch (ViewException) {
75
            // Fallback to default view in case if specific view not found
76
            $view = $this->views->get(self::DEFAULT_VIEW);
77
        }
78
79
        $content = $view->render(['code' => $code, 'exception' => $exception]);
80
        $response->getBody()->write($content);
81
82
        return $response;
83
    }
84
}
85