Passed
Push — master ( 8e9e8c...5c7da6 )
by Fran
03:59
created

CustomTranslateExtension::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
namespace PSFS\base\extension;
4
5
use PSFS\base\config\Config;
6
use PSFS\base\Logger;
7
use PSFS\base\Security;
8
use PSFS\base\types\helpers\I18nHelper;
9
use PSFS\base\types\traits\SingletonTrait;
10
use Twig\Extension\AbstractExtension;
11
use Twig\Extensions\TokenParser\TransTokenParser;
12
use Twig\TwigFilter;
13
14
/**
15
 * Class CustomTranslateExtension
16
 * @package PSFS\base\extension
17
 */
18
class CustomTranslateExtension extends AbstractExtension
19
{
20
    use SingletonTrait;
21
22
    const CUSTOM_LOCALE_SESSION_KEY = '__PSFS_CUSTOM_LOCALE_KEY__';
23
    const LOCALE_CACHED_VERSION = '__PSFS_LOCALE_VERSION__';
24
    const LOCALE_CACHED_TAG = '__PSFS_TRANSLATIONS__';
25
26
    /**
27
     * @var array
28
     */
29
    protected static $translations = [];
30
    /**
31
     * @var string
32
     */
33
    protected static $locale = 'es_ES';
34
    /**
35
     * @var bool
36
     */
37
    protected static $generate = false;
38
    /**
39
     * @var string
40
     */
41
    protected static $filename = '';
42
43
    /**
44
     * @param string $customKey
45
     * @param bool $forceReload
46
     * @param bool $useBase
47
     */
48 7
    protected static function checkLoad($customKey = null, $forceReload = false, $useBase = false)
49
    {
50 7
        $session = Security::getInstance();
51 7
        self::$locale = I18nHelper::extractLocale($session->getSessionKey(I18nHelper::PSFS_SESSION_LANGUAGE_KEY));
0 ignored issues
show
Documentation Bug introduced by
It seems like PSFS\base\types\helpers\..._SESSION_LANGUAGE_KEY)) can also be of type array. However, the property $locale is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
52 7
        $version = self::$locale . '_' . $session->getSessionKey(self::LOCALE_CACHED_VERSION);
0 ignored issues
show
Bug introduced by
Are you sure self::locale of type array|mixed|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

52
        $version = /** @scrutinizer ignore-type */ self::$locale . '_' . $session->getSessionKey(self::LOCALE_CACHED_VERSION);
Loading history...
53 7
        $configVersion = self::$locale . '_' . $session->getSessionKey('config.cache.var');
54 7
        if ($forceReload) {
55
            self::dropInstance();
56
            $version = null;
57
        }
58 7
        self::$generate = (boolean)Config::getParam('i18n.autogenerate', false);
59 7
        if(null !== $version && $version !== $configVersion) {
60
            self::$translations = $session->getSessionKey(self::LOCALE_CACHED_TAG);
61
        } else {
62 7
            if (!$useBase) {
63 7
                $customKey = $customKey ?: $session->getSessionKey(self::CUSTOM_LOCALE_SESSION_KEY);
64
            }
65
            // Gather always the base translations
66 7
            $standardTranslations = [];
67 7
            self::$filename = implode(DIRECTORY_SEPARATOR, [LOCALE_DIR, 'custom', self::$locale . '.json']);
68 7
            if(file_exists(self::$filename)) {
69
                $standardTranslations = json_decode(file_get_contents(self::$filename), true);
70
            }
71
            // If the project has custom translations, gather them
72 7
            if (null !== $customKey) {
73
                Logger::log('[' . self::class . '] Custom key detected: ' . $customKey, LOG_INFO);
74
                self::$filename = implode(DIRECTORY_SEPARATOR, [LOCALE_DIR, 'custom', $customKey, self::$locale . '.json']);
75
            }
76
            // Finally we merge base and custom translations to complete all the i18n set
77 7
            if (file_exists(self::$filename)) {
78
                Logger::log('[' . self::class . '] Custom locale detected: ' . $customKey . ' [' . self::$locale . ']', LOG_INFO);
79
                self::$translations = array_merge($standardTranslations, json_decode(file_get_contents(self::$filename), true));
80
                $session->setSessionKey(self::LOCALE_CACHED_TAG, self::$translations);
81
                $session->setSessionKey(self::LOCALE_CACHED_VERSION, $configVersion);
82 7
            } elseif (null !== $customKey) {
83
                self::checkLoad(null, $forceReload, true);
84
            }
85
        }
86
87 7
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92 1
    public function getTokenParsers()
93
    {
94 1
        return array(new  TransTokenParser());
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100 1
    public function getFilters()
101
    {
102
        return array(
103
            new TwigFilter('trans', function ($message) {
104 1
                return self::_($message);
105 1
            }),
106
        );
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112
    public function getName()
113
    {
114
        return 'PSFSi18n';
115
    }
116
117
    /**
118
     * @param $message
119
     * @param string $customKey
120
     * @param bool $forceReload
121
     * @return mixed|string
122
     */
123 7
    public static function _($message, $customKey = null, $forceReload = false)
124
    {
125 7
        self::checkLoad($customKey, $forceReload);
126 7
        if (is_array(self::$translations) && array_key_exists($message, self::$translations)) {
127
            $translation = self::$translations[$message];
128
        } else {
129 7
            $translation = gettext($message);
130
        }
131 7
        if (self::$generate) {
132
            self::generate($message, $translation);
133
        }
134 7
        return $translation;
135
    }
136
137
    /**
138
     * @param string $message
139
     * @param string $translation
140
     */
141
    protected static function generate($message, $translation)
142
    {
143
        if (!array_key_exists($message, self::$translations)) {
144
            self::$translations[$message] = $translation;
145
        }
146
        file_put_contents(self::$filename, json_encode(array_unique(self::$translations), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
147
    }
148
}
149