/
CanonicalizeRuntime.php
70 lines (57 loc) · 2.05 KB
/
CanonicalizeRuntime.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\Form\Twig;
use Symfony\Component\HttpFoundation\RequestStack;
use Twig\Extension\RuntimeExtensionInterface;
final class CanonicalizeRuntime implements RuntimeExtensionInterface
{
// @todo: there are more locales which are not supported by "Moment.js" NPM library and they need to be translated/normalized/canonicalized here
private const MOMENT_UNSUPPORTED_LOCALES = [
'de' => ['de', 'de-at'],
'es' => ['es', 'es-do'],
'nl' => ['nl', 'nl-be'],
'fr' => ['fr', 'fr-ca', 'fr-ch'],
];
private RequestStack $requestStack;
/**
* @internal This class should only be used through Twig
*/
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
/**
* Returns a canonicalized locale for "Moment.js" NPM library,
* or `null` if the locale's language is "en", which doesn't require localization.
*/
public function getCanonicalizedLocaleForMoment(): ?string
{
$locale = $this->getLocale();
// "en" language doesn't require localization.
if (('en' === $lang = substr($locale, 0, 2)) && !\in_array($locale, ['en-au', 'en-ca', 'en-gb', 'en-ie', 'en-nz'], true)) {
return null;
}
foreach (self::MOMENT_UNSUPPORTED_LOCALES as $language => $locales) {
if ($language === $lang && !\in_array($locale, $locales, true)) {
$locale = $language;
}
}
return $locale;
}
private function getLocale(): string
{
$request = $this->requestStack->getCurrentRequest();
if (null === $request) {
throw new \LogicException('The request stack is empty.');
}
return str_replace('_', '-', $request->getLocale());
}
}