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
|
|
|
|