Completed
Push — master ( 8a7e9a...c767d2 )
by Paweł
422:02 queued 408:26
created

RequestBasedLocaleContext::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
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\LocaleBundle\Context;
13
14
use Sylius\Component\Locale\Context\LocaleContextInterface;
15
use Sylius\Component\Locale\Context\LocaleNotFoundException;
16
use Sylius\Component\Locale\Provider\LocaleProviderInterface;
17
use Symfony\Component\HttpFoundation\RequestStack;
18
19
/**
20
 * @author Kamil Kokot <[email protected]>
21
 */
22
final class RequestBasedLocaleContext implements LocaleContextInterface
23
{
24
    /**
25
     * @var RequestStack
26
     */
27
    private $requestStack;
28
29
    /**
30
     * @var LocaleProviderInterface
31
     */
32
    private $localeProvider;
33
34
    /**
35
     * @param RequestStack $requestStack
36
     * @param LocaleProviderInterface $localeProvider
37
     */
38
    public function __construct(RequestStack $requestStack, LocaleProviderInterface $localeProvider)
39
    {
40
        $this->requestStack = $requestStack;
41
        $this->localeProvider = $localeProvider;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function getLocaleCode()
48
    {
49
        $request = $this->requestStack->getMasterRequest();
50
        if (null === $request) {
51
            throw new LocaleNotFoundException('No master request available.');
52
        }
53
54
        $localeCode = $request->attributes->get('_locale');
55
        if (null === $localeCode) {
56
            throw new LocaleNotFoundException('No locale attribute is set on the master request.');
57
        }
58
59
        $availableLocalesCodes = $this->localeProvider->getAvailableLocalesCodes();
60
        if (!in_array($localeCode, $availableLocalesCodes, true)) {
61
            throw LocaleNotFoundException::notAvailable($localeCode, $availableLocalesCodes);
62
        }
63
64
        return $localeCode;
65
    }
66
}
67