ResponseFormatterListener::getRouter()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace ScayTrase\Api\Cruds\Listener;
4
5
use Symfony\Component\HttpFoundation\Response;
6
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
7
use Symfony\Component\Routing\RouterInterface;
8
use Symfony\Component\Serializer\SerializerInterface;
9
10
final class ResponseFormatterListener
11
{
12
    private static $formatMap = [
13
        'json' => 'application/json',
14
        'xml'  => 'application/xml',
15
        'yaml' => 'application/x-yaml',
16
        'yml'  => 'application/x-yaml',
17
    ];
18
19
    use CrudsRequestCheckerTrait;
20
21
    /** @var  SerializerInterface */
22
    private $serializer;
23
    /** @var RouterInterface */
24
    private $router;
25
26
    /**
27
     * ResponseNormalizerListener constructor.
28
     *
29
     * @param SerializerInterface $serializer
30
     * @param RouterInterface     $router
31
     */
32 26
    public function __construct(SerializerInterface $serializer, RouterInterface $router)
33
    {
34 26
        $this->router     = $router;
35 26
        $this->serializer = $serializer;
36 26
    }
37
38 26
    public function filterResponse(GetResponseForControllerResultEvent $event)
39
    {
40 26
        if (!$this->checkRequest($event)) {
41
            return;
42
        }
43
44 26
        $request  = $event->getRequest();
45 26
        $response = $event->getControllerResult();
46
47 26
        $format = $request->get('_format', 'json');
48
49 26
        $content     = $this->serializer->serialize($response, $format);
50 26
        $contentType = array_key_exists($format, self::$formatMap) ? self::$formatMap[$format] : 'text/plain';
51 26
        $event->setResponse(
52 26
            new Response(
53 26
                $content,
54 26
                Response::HTTP_OK,
55
                [
56 26
                    'Content-Type' => $contentType,
57
                ]
58
            )
59
        );
60 26
    }
61
62
    /** {@inheritdoc} */
63
    protected function getRouter()
64
    {
65
        return $this->router;
66
    }
67
}
68