Completed
Pull Request — master (#26)
by Valentyn
02:41
created

translateArrayOfEntities()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
ccs 5
cts 5
cp 1
rs 9.6666
cc 2
eloc 5
nc 2
nop 2
crap 2
1
<?php
2
3
namespace App\Translation\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 6
        if (is_object($result) === true && $result instanceof TranslatableInterface) {
37
            // If its single entity response
38 2
            $response = $this->serializer->serialize($result, $event->getRequest()->getLocale());
39 2
            $event->setControllerResult($response);
40 2
            return;
41
        }
42 4
    }
43
44 3
    private function translateArrayOfEntities(array $entities, string $locale): array
45
    {
46 3
        $translatedEntities = [];
47 3
        foreach ($entities as $entity) {
48 3
            $translatedEntities[] = $this->serializer->serialize($entity, $locale);
49
        }
50
51 3
        return $translatedEntities;
52
    }
53
54 1
    public static function getSubscribedEvents()
55
    {
56
        return [
57 1
            KernelEvents::VIEW => ['onKernelView', 60],
58
        ];
59
    }
60
}