Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
69.23% covered (warning)
69.23%
9 / 13
50.00% covered (danger)
50.00%
3 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApieErrorRenderer
69.23% covered (warning)
69.23%
9 / 13
50.00% covered (danger)
50.00%
3 / 6
12.91
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isApieRequest
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 canCreateCmsResponse
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 createApiResponse
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createCmsResponse
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 renderException
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace Apie\LaravelApie\ErrorHandler;
4
5use Apie\Common\ErrorHandler\ApiErrorRenderer as CommonApiErrorRenderer;
6use Apie\Core\ContextConstants;
7use Apie\HtmlBuilders\ErrorHandler\CmsErrorRenderer;
8use Apie\HtmlBuilders\ErrorHandler\StacktraceRenderer;
9use Illuminate\Http\Request;
10use Symfony\Component\HttpFoundation\Response;
11use Throwable;
12
13class ApieErrorRenderer
14{
15    public function __construct(
16        private readonly ?CmsErrorRenderer $cmsErrorRenderer,
17        private readonly CommonApiErrorRenderer $apiErrorRenderer,
18        private readonly string $cmsBaseUrl
19    ) {
20    }
21
22    public function isApieRequest(Request $request): bool
23    {
24        return $request->attributes->has('_is_apie') ||
25            $this->canCreateCmsResponse($request);
26    }
27
28    public function canCreateCmsResponse(Request $request): bool
29    {
30        if ($request->attributes->has(ContextConstants::CMS)
31            && null !== $this->cmsErrorRenderer
32        ) {
33            return true;
34        }
35        return str_starts_with($request->getPathInfo(), $this->cmsBaseUrl);
36    }
37
38    public function createApiResponse(Throwable $error): Response
39    {
40        return $this->apiErrorRenderer->createApiResponse($error);
41    }
42
43    public function createCmsResponse(Request $request, Throwable $error): Response
44    {
45        if (!$this->cmsErrorRenderer) {
46            return new Response("Internal error", 500);
47        }
48        return $this->cmsErrorRenderer->createCmsResponse($request, $error);
49    }
50
51    public static function renderException(Throwable $throwable): string
52    {
53        $renderer = new StacktraceRenderer($throwable);
54        return (string) $renderer;
55    }
56}