Passed
Branch improve-scrutinizer (747e36)
by Ayan
05:23
created

JsonXml::format()   A

Complexity

Conditions 6
Paths 2

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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