1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Phprest\ErrorHandler\Formatter; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use League\BooBoo\Formatter\AbstractFormatter; |
7
|
|
|
use League\Container\ContainerInterface; |
8
|
|
|
use Phprest\Application; |
9
|
|
|
use Phprest\Config; |
10
|
|
|
use Phprest\Entity; |
11
|
|
|
use Phprest\Service; |
12
|
|
|
use Symfony\Component\HttpFoundation\Request; |
13
|
|
|
use Symfony\Component\HttpFoundation\Response; |
14
|
|
|
|
15
|
|
|
class JsonXml extends AbstractFormatter |
16
|
|
|
{ |
17
|
|
|
use Service\Hateoas\Getter; |
18
|
|
|
use Service\Hateoas\Util; |
|
|
|
|
19
|
|
|
|
20
|
|
|
protected Config $config; |
21
|
|
|
protected ?Request $request; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param Config $config |
25
|
|
|
* @param null|Request $request |
26
|
|
|
*/ |
27
|
69 |
|
public function __construct(Config $config, Request $request = null) |
28
|
|
|
{ |
29
|
69 |
|
$this->config = $config; |
30
|
69 |
|
$this->request = $request; |
31
|
69 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param Exception $exception |
35
|
|
|
* |
36
|
|
|
* @return string |
37
|
|
|
*/ |
38
|
|
|
public function format($exception) |
39
|
|
|
{ |
40
|
|
|
$response = new Response(); |
41
|
|
|
|
42
|
|
|
try { |
43
|
|
|
$response = $this->serialize( |
44
|
|
|
$this->config->isDebug() ? new Entity\DebugError($exception) : new Entity\Error($exception), |
45
|
|
|
is_null($this->request) ? Request::createFromGlobals() : $this->request, |
46
|
|
|
$response |
47
|
|
|
); |
48
|
|
|
} catch (Exception $e) { |
49
|
|
|
$response->setContent( |
50
|
|
|
$this->serviceHateoas()->getSerializer()->serialize( |
51
|
|
|
$this->config->isDebug() ? new Entity\DebugError($e) : new Entity\Error($e), |
52
|
|
|
'json' |
53
|
|
|
) |
54
|
|
|
); |
55
|
|
|
|
56
|
|
|
$vendor = $this->getContainer()->get(Application::CONTAINER_ID_VENDOR); |
57
|
|
|
$apiVersion = $this->getContainer()->get(Application::CONTAINER_ID_API_VERSION); |
58
|
|
|
|
59
|
|
|
$response->headers->set('Content-Type', 'application/vnd.' . $vendor . '-v' . $apiVersion . '+json'); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$response->setStatusCode(method_exists($exception, 'getStatusCode') ? $exception->getStatusCode() : 500); |
63
|
|
|
|
64
|
|
|
$response->sendHeaders(); |
65
|
|
|
|
66
|
|
|
return $response->getContent(); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return ContainerInterface |
71
|
|
|
*/ |
72
|
|
|
public function getContainer() |
73
|
|
|
{ |
74
|
|
|
return $this->config->getContainer(); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|