1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of coisa/error-handler. |
5
|
|
|
* |
6
|
|
|
* (c) Felipe Sayão Lobato Abreu <[email protected]> |
7
|
|
|
* |
8
|
|
|
* This source file is subject to the license that is bundled |
9
|
|
|
* with this source code in the file LICENSE. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace CoiSA\ErrorHandler\Http\Message; |
15
|
|
|
|
16
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
17
|
|
|
use Psr\Http\Message\ResponseInterface; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Class ThrowableResponseFactory |
21
|
|
|
* |
22
|
|
|
* @package CoiSA\ErrorHandler\Http\Message |
23
|
|
|
*/ |
24
|
|
|
final class ThrowableResponseFactory implements ThrowableResponseFactoryInterface |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @var ThrowableStreamFactoryInterface |
28
|
|
|
*/ |
29
|
|
|
private $streamFactory; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var ResponseFactoryInterface |
33
|
|
|
*/ |
34
|
|
|
private $responseFactory; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* ThrowableResponseFactory constructor. |
38
|
|
|
* |
39
|
|
|
* @param ThrowableStreamFactoryInterface $streamFactory |
40
|
|
|
* @param ResponseFactoryInterface $responseFactory |
41
|
|
|
*/ |
42
|
13 |
|
public function __construct( |
43
|
|
|
ThrowableStreamFactoryInterface $streamFactory, |
44
|
|
|
ResponseFactoryInterface $responseFactory |
45
|
|
|
) { |
46
|
13 |
|
$this->streamFactory = $streamFactory; |
47
|
13 |
|
$this->responseFactory = $responseFactory; |
48
|
13 |
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param \Throwable $throwable |
52
|
|
|
* |
53
|
|
|
* @return ResponseInterface |
54
|
|
|
*/ |
55
|
2 |
|
public function createResponseFromThrowable(\Throwable $throwable): ResponseInterface |
56
|
|
|
{ |
57
|
2 |
|
$code = $throwable->getCode(); |
58
|
2 |
|
$message = $throwable->getMessage(); |
59
|
|
|
|
60
|
2 |
|
$statusCode = $this->getStatusCode($code); |
61
|
|
|
|
62
|
2 |
|
$response = $this->responseFactory->createResponse($statusCode, $message); |
63
|
2 |
|
$stream = $this->streamFactory->createStreamFromThrowable($throwable); |
64
|
|
|
|
65
|
2 |
|
return $response->withBody($stream); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param int $code |
70
|
|
|
* |
71
|
|
|
* @return int |
72
|
|
|
*/ |
73
|
2 |
|
private function getStatusCode(int $code): int |
74
|
|
|
{ |
75
|
2 |
|
return $code >= 400 && $code <= 500 ? $code : 500; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|