Completed
Pull Request — master (#21)
by Valentyn
01:42
created

TranslatedEntityResponseListener::onKernelView()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 13
cts 13
cp 1
rs 8.6737
c 0
b 0
f 0
cc 6
eloc 12
nc 5
nop 1
crap 6
1
<?php
2
3
namespace App\EventListener;
4
5
use App\Translation\TranslatableInterface;
6
use App\Translation\TranslatedEntitySerializer;
7
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
8
use Symfony\Component\HttpKernel\KernelEvents;
9
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
10
11
class TranslatedEntityResponseListener implements EventSubscriberInterface
12
{
13
    private $serializer;
14
15 9
    public function __construct(TranslatedEntitySerializer $serializer)
16
    {
17 9
        $this->serializer = $serializer;
18 9
    }
19
20
    // todo what if I need to return something like {items: {..translated entities..}, pagination: {page: 1: items: 500}}
21
    // How to translate this type of response? Think about it..
22 9
    public function onKernelView(GetResponseForControllerResultEvent $event)
23
    {
24 9
        $result = $event->getControllerResult();
25
26 9
        if (is_array($result) === true) {
27 5
            $probablyEntity = reset($result);
28 5
            if (is_object($probablyEntity) && $result[0] instanceof TranslatableInterface) {
29
                // If its array of translated entities
30 3
                $response = $this->translateArrayOfEntities($result, $event->getRequest()->getLocale());
31 3
                $event->setControllerResult($response);
32 3
                return;
33
            }
34
        }
35
36
37 6
        if (is_object($result) === true && $result instanceof TranslatableInterface) {
38
            // If its single entity response
39 2
            $response = $this->serializer->serialize($result, $event->getRequest()->getLocale());
40 2
            $event->setControllerResult($response);
41 2
            return;
42
        }
43 4
    }
44
45 3
    private function translateArrayOfEntities(array $entities, string $locale): array
46
    {
47 3
        $translatedEntities = [];
48 3
        foreach ($entities as $entity) {
49 3
            $translatedEntities[] = $this->serializer->serialize($entity, $locale);
50
        }
51
52 3
        return $translatedEntities;
53
    }
54
55 1
    public static function getSubscribedEvents()
56
    {
57
        return [
58 1
            KernelEvents::VIEW => ['onKernelView', 60],
59
        ];
60
    }
61
}