|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Bone\I18n; |
|
4
|
|
|
|
|
5
|
|
|
use Barnacle\Container; |
|
6
|
|
|
use Barnacle\Exception\NotFoundException; |
|
7
|
|
|
use Barnacle\RegistrationInterface; |
|
8
|
|
|
use Bone\Http\Middleware\Stack; |
|
9
|
|
|
use Bone\Http\MiddlewareAwareInterface; |
|
10
|
|
|
use Bone\I18n\Http\Middleware\I18nMiddleware; |
|
11
|
|
|
use Bone\I18n\View\Extension\LocaleLink; |
|
12
|
|
|
use Bone\I18n\View\Extension\Translate; |
|
13
|
|
|
use Bone\View\ViewEngine; |
|
14
|
|
|
use Bone\I18n\Service\TranslatorFactory; |
|
15
|
|
|
use Laminas\I18n\Translator\Translator; |
|
16
|
|
|
use Locale; |
|
17
|
|
|
|
|
18
|
|
|
class I18nPackage implements RegistrationInterface, MiddlewareAwareInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @param Container $c |
|
22
|
|
|
* @throws Exception |
|
23
|
|
|
*/ |
|
24
|
|
|
public function addToContainer(Container $c) |
|
25
|
|
|
{ |
|
26
|
|
|
if ($c->has('i18n')) { |
|
27
|
|
|
$i18n = $c->get('i18n'); |
|
28
|
|
|
$factory = new TranslatorFactory(); |
|
29
|
|
|
$translator = $factory->createTranslator($i18n); |
|
30
|
|
|
$engine = $c->get(ViewEngine::class); |
|
31
|
|
|
$engine->loadExtension(new Translate($translator)); |
|
32
|
|
|
$engine->loadExtension(new LocaleLink($i18n['enabled'])); |
|
33
|
|
|
$defaultLocale = $i18n['default_locale'] ?: 'en_GB'; |
|
34
|
|
|
$translator->setLocale($defaultLocale); |
|
35
|
|
|
Locale::setDefault($defaultLocale); |
|
36
|
|
|
$c[Translator::class] = $translator; |
|
37
|
|
|
} else { |
|
38
|
|
|
throw new NotFoundException('I18nPackage is registered but there is no i18n config. See the |
|
39
|
|
|
delboy1978uk/bone-i18n README.', 418); |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @param Stack $stack |
|
45
|
|
|
*/ |
|
46
|
|
|
public function addMiddleware(Stack $stack, Container $c): void |
|
47
|
|
|
{ |
|
48
|
|
|
if ($c->has('i18n')) { |
|
49
|
|
|
$i18n = $c->get('i18n'); |
|
50
|
|
|
$translator = $c->get(Translator::class); |
|
51
|
|
|
$i18nMiddleware = new I18nMiddleware($translator, $i18n['supported_locales'], $i18n['default_locale'], $i18n['enabled']); |
|
52
|
|
|
$stack->addMiddleWare($i18nMiddleware); |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|