I18nPackage::getGlobalMiddleware()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
ccs 0
cts 0
cp 0
rs 10
cc 3
nc 2
nop 1
crap 12
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\GlobalMiddlewareRegistrationInterface;
9
use Bone\Http\Middleware\Stack;
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, GlobalMiddlewareRegistrationInterface
19
{
20
    /**
21
     * @param Container $c
22
     * @throws Exception
23
     */
24 5
    public function addToContainer(Container $c)
25
    {
26 5
        if ($c->has('i18n')) {
27 4
            $i18n = $c->get('i18n');
28 4
            $factory = new TranslatorFactory();
29 4
            $translator = $factory->createTranslator($i18n);
30 4
            $engine = $c->get(ViewEngine::class);
31 4
            $engine->loadExtension(new Translate($translator));
32 4
            $engine->loadExtension(new LocaleLink($i18n['enabled']));
33 4
            $defaultLocale = $i18n['default_locale'] ?: 'en_GB';
34 4
            $translator->setLocale($defaultLocale);
35 4
            Locale::setDefault($defaultLocale);
36 4
            $c[Translator::class] = $translator;
37
        } else {
38 1
            throw new NotFoundException('I18nPackage is registered but there is no i18n config. See the 
39 1
            delboy1978uk/bone-i18n README.', 418);
40
        }
41 4
    }
42
43
    /**
44
     * @param Container $c
45
     * @return array
46 4
     */
47
    public function getMiddleware(Container $c): array
48 4
    {
49 4
        if ($c->has('i18n')) {
50 4
            $i18n = $c->get('i18n');
51 4
            $translator = $c->get(Translator::class);
52 4
            $i18nMiddleware = new I18nMiddleware($translator, $i18n['supported_locales'], $i18n['default_locale'], $i18n['enabled']);
53
54 4
            return [$i18nMiddleware];
55
        }
56
57
        return [];
58
    }
59
60
    /**
61
     * @return array
62
     */
63
    public function getGlobalMiddleware(Container $c): array
64
    {
65
        if ($c->has('i18n') && $c->get('i18n')['enabled']) {
66
            return [I18nMiddleware::class];
67
        }
68
69
        return [];
70
    }
71
}
72