Completed
Push — master ( 6cae80...ac9c80 )
by Tomáš
04:55
created

LanguageDefaultSubscriber::setDefault()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 29
ccs 16
cts 16
cp 1
rs 6.7272
c 1
b 0
f 0
cc 7
eloc 16
nc 4
nop 1
crap 7
1
<?php
2
3
namespace Webcook\Cms\I18nBundle\EventSubscriber;
4
5
use ApiPlatform\Core\EventListener\EventPriorities;
6
use Webcook\Cms\I18nBundle\Entity\Language;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
10
use Symfony\Component\HttpKernel\KernelEvents;
11
12
final class LanguageDefaultSubscriber implements EventSubscriberInterface
13
{
14
    private $em;
15
16 12
    public function __construct($em)
17
    {
18 12
        $this->em = $em;
19 12
    }
20
21 14
    public static function getSubscribedEvents()
22
    {
23
        return [
24 14
            KernelEvents::VIEW => [['setDefault', EventPriorities::POST_WRITE]],
25
        ];
26
    }
27
28 10
    public function setDefault(GetResponseForControllerResultEvent $event)
29
    {
30 10
        $language = $event->getControllerResult();
31 10
        $method = $event->getRequest()->getMethod();
32
33 10
        if (!$language instanceof Language) {
34 7
            return;
35
        }
36
37 3
        if ($language->isDefault()) {
38 3
            if (Request::METHOD_POST === $method || Request::METHOD_PUT === $method) {
39 2
                $languages = $this->em->getRepository('Webcook\Cms\I18nBundle\Entity\Language')->findBy(array(
40
                    'default' => true
41 2
                ));
42
43 2
                foreach ($languages as $l) {
44 2
                    if ($l !== $language) {
45 2
                        $l->setDefault(false);
46
                    }
47
                }
48
            } else {
49 1
                $language = $this->em->getRepository('Webcook\Cms\I18nBundle\Entity\Language')->findAll()[0];
50
51 1
                $language->setDefault(true);
52
            }
53
        }
54
55 3
        $this->em->flush();
56
    }
57
}