I18nPackage   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 1
Metric Value
wmc 8
eloc 24
c 5
b 0
f 1
dl 0
loc 52
ccs 22
cts 22
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addToContainer() 0 16 3
A getMiddleware() 0 11 2
A getGlobalMiddleware() 0 7 3
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