Test Failed
Pull Request — master (#5)
by Ayan
03:44
created

JsonXml::getContainer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 1
c 1
b 1
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
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;
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...
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