Passed
Push — master ( 7b436a...c19eb6 )
by Fran
03:33
created

CustomTranslateExtension::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.125

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 13
ccs 5
cts 10
cp 0.5
crap 4.125
rs 9.4285
1
<?php
2
namespace PSFS\base\extension;
3
4
use PSFS\base\Logger;
5
use PSFS\base\Security;
6
use PSFS\base\types\helpers\I18nHelper;
7
8
/**
9
 * Class CustomTranslateExtension
10
 * @package PSFS\base\extension
11
 */
12
class CustomTranslateExtension extends \Twig_Extension {
13
    const CUSTOM_LOCALE_SESSION_KEY = '__PSFS_CUSTOM_LOCALE_KEY__';
14
15
    protected $translations = [];
16
    protected $locale = 'es_ES';
17
18 1
    public function __construct()
19
    {
20 1
        $this->locale = I18nHelper::extractLocale('es_ES');
21 1
        $custom_key = Security::getInstance()->getSessionKey(self::CUSTOM_LOCALE_SESSION_KEY);
22 1
        if(null !== $custom_key) {
23
            Logger::log('[' . self::class . '] Custom key detected: ' . $custom_key, LOG_INFO);
24
            $filename = implode(DIRECTORY_SEPARATOR, [LOCALE_DIR, 'custom', $custom_key, $this->locale . '.json']);
25
            if(file_exists($filename)) {
26
                Logger::log('[' . self::class . '] Custom locale detected: ' . $custom_key . ' [' . $this->locale . ']', LOG_INFO);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 131 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
27
                $this->translations = json_decode(file_get_contents($filename), true);
28
            }
29
        }
30 1
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35 1
    public function getTokenParsers()
36
    {
37 1
        return array(new \Twig_Extensions_TokenParser_Trans());
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function getFilters()
44
    {
45
        return array(
46 1
            new \Twig_SimpleFilter('trans', function($message) {
47 1
                if(array_key_exists($message, $this->translations)) {
48
                    return $this->translations[$message];
49
                } else {
50 1
                    return gettext($message);
51
                }
52 1
            }),
53
        );
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 1
    public function getName()
60
    {
61 1
        return 'PSFSi18n';
62
    }
63
}