ResponseFormatterListener   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 85%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 5
lcom 1
cbo 5
dl 0
loc 58
ccs 17
cts 20
cp 0.85
rs 10
c 1
b 1
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A filterResponse() 0 23 3
A getRouter() 0 4 1
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