Passed
Push — master ( 5c7da6...2e1684 )
by Fran
02:26
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 = $session->getSessionKey(self::LOCALE_CACHED_VERSION);
53 7
        $configVersion = self::$locale . '_' . Config::getParam('cache.var', 'v1');
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

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