Completed
Push — master ( 68bcee...8562e3 )
by Michał
17:05 queued 08:30
created

ChannelFormSubscriber::resolveLocales()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Bundle\CoreBundle\Form\EventSubscriber;
13
14
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
15
use Symfony\Component\Form\FormEvent;
16
use Symfony\Component\Form\FormEvents;
17
18
/**
19
 * @author Grzegorz Sadowski <[email protected]>
20
 */
21
final class ChannelFormSubscriber implements EventSubscriberInterface
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public static function getSubscribedEvents()
27
    {
28
        return [
29
            FormEvents::PRE_SUBMIT => 'preSubmit',
30
        ];
31
    }
32
33
    /**
34
     * @param FormEvent $event
35
     */
36
    public function preSubmit(FormEvent $event)
37
    {
38
        $data = $event->getData();
39
40
        if (empty($data) || empty($data['defaultLocale']) || empty($data['baseCurrency'])) {
41
            return;
42
        }
43
44
        $data['locales'] = $this->resolveLocales(
45
            empty($data['locales']) ? [] : $data['locales'],
46
            $data['defaultLocale'])
47
        ;
48
49
        $data['currencies'] = $this->resolveCurrencies(
50
            empty($data['currencies']) ? [] : $data['currencies'],
51
            $data['baseCurrency'])
52
        ;
53
54
        $event->setData($data);
55
    }
56
57
    /**
58
     * @param string[] $locales
59
     * @param string $defaultLocale
60
     *
61
     * @return string[]
62
     */
63
    private function resolveLocales(array $locales, $defaultLocale)
64
    {
65
        if (empty($locales)) {
66
            return [$defaultLocale];
67
        }
68
69
        if (!in_array($defaultLocale, $locales)) {
70
            $locales[] = $defaultLocale;
71
        }
72
73
        return $locales;
74
    }
75
76
    /**
77
     * @param string[] $currencies
78
     * @param string $baseCurrency
79
     *
80
     * @return string[]
81
     */
82
    private function resolveCurrencies(array $currencies, $baseCurrency)
83
    {
84
        if (empty($currencies)) {
85
            return [$baseCurrency];
86
        }
87
88
        if (!in_array($baseCurrency, $currencies)) {
89
            $currencies[] = $baseCurrency;
90
        }
91
92
        return $currencies;
93
    }
94
}
95