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