Test Failed
Push — master ( 1b7368...050678 )
by Fran
25:16 queued 22:49
created

CustomTranslateExtension::generate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 6
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\helpers\Inspector;
10
use PSFS\base\types\traits\SingletonTrait;
11
use Twig\Extension\AbstractExtension;
12
use Twig\TokenParser\BlockTokenParser;
13
use Twig\TwigFilter;
14
15
/**
16
 * Class CustomTranslateExtension
17
 * @package PSFS\base\extension
18
 */
19
class CustomTranslateExtension extends AbstractExtension
20
{
21
    use SingletonTrait;
22
23
    const CUSTOM_LOCALE_SESSION_KEY = '__PSFS_CUSTOM_LOCALE_KEY__';
24
    const LOCALE_CACHED_VERSION = '__PSFS_LOCALE_VERSION__';
25
    const LOCALE_CACHED_TAG = '__PSFS_TRANSLATIONS__';
26
27
    /**
28
     * @var array
29
     */
30
    protected static $translations = [];
31
    /**
32
     * @var string
33
     */
34
    protected static $locale = 'es_ES';
35
    /**
36
     * @var bool
37
     */
38
    protected static $generate = false;
39
    /**
40
     * @var string
41
     */
42
    protected static $filename = '';
43
44
    /**
45
     * @return array|mixed
46
     */
47 1
    protected static function extractBaseTranslations()
48
    {
49
        // Gather always the base translations
50 1
        $standardTranslations = [];
51 1
        self::$filename = implode(DIRECTORY_SEPARATOR, [LOCALE_DIR, 'custom', self::$locale . '.json']);
52 1
        if (file_exists(self::$filename)) {
53 1
            $standardTranslations = json_decode(file_get_contents(self::$filename), true);
54
        }
55 1
        return $standardTranslations;
56
    }
57
58
    /**
59
     * @param string $customKey
60
     * @param bool $forceReload
61
     * @param bool $useBase
62
     */
63 1
    protected static function translationsCheckLoad($customKey = null, $forceReload = false, $useBase = false)
64
    {
65 1
        Inspector::stats('[translationsCheckLoad] Start checking translations load', Inspector::SCOPE_DEBUG);
66 1
        $session = Security::getInstance();
67 1
        self::$locale = I18nHelper::extractLocale($session->getSessionKey(I18nHelper::PSFS_SESSION_LANGUAGE_KEY));
68 1
        $version = $session->getSessionKey(self::LOCALE_CACHED_VERSION);
69 1
        $configVersion = self::$locale . '_' . Config::getParam('cache.var', 'v1');
70 1
        if ($forceReload) {
71
            Inspector::stats('[translationsCheckLoad] Force translations reload', Inspector::SCOPE_DEBUG);
72
            self::dropInstance();
73
            $version = null;
74
            self::$translations = [];
75
        }
76 1
        if(count(self::$translations) === 0) {
77 1
            Inspector::stats('[translationsCheckLoad] Extracting translations', Inspector::SCOPE_DEBUG);
78 1
            self::$generate = (boolean)Config::getParam('i18n.autogenerate', false);
79 1
            if(null !== $version && $version === $configVersion) {
80
                Inspector::stats('[translationsCheckLoad] Translations loaded from session', Inspector::SCOPE_DEBUG);
81
                self::$translations = $session->getSessionKey(self::LOCALE_CACHED_TAG);
82
            } else {
83 1
                if (!$useBase) {
84 1
                    $customKey = $customKey ?: $session->getSessionKey(self::CUSTOM_LOCALE_SESSION_KEY);
85
                }
86 1
                $standardTranslations = self::extractBaseTranslations();
87
                // If the project has custom translations, gather them
88 1
                if (null !== $customKey) {
89
                    Logger::log('[' . self::class . '] Custom key detected: ' . $customKey, LOG_INFO);
90
                    self::$filename = implode(DIRECTORY_SEPARATOR, [LOCALE_DIR, 'custom', $customKey, self::$locale . '.json']);
91
                }
92
                // Finally we merge base and custom translations to complete all the i18n set
93 1
                if (file_exists(self::$filename)) {
94 1
                    Logger::log('[' . self::class . '] Custom locale detected: ' . $customKey . ' [' . self::$locale . ']', LOG_INFO);
95 1
                    self::$translations = array_merge($standardTranslations, json_decode(file_get_contents(self::$filename), true));
96 1
                    $session->setSessionKey(self::LOCALE_CACHED_TAG, self::$translations);
97 1
                    $session->setSessionKey(self::LOCALE_CACHED_VERSION, $configVersion);
98
                } elseif (null !== $customKey) {
99
                    self::translationsCheckLoad(null, $forceReload, true);
100
                }
101
            }
102
        }
103 1
        Inspector::stats('[translationsCheckLoad] Translations loaded', Inspector::SCOPE_DEBUG);
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109 1
    public function getTokenParsers()
110
    {
111 1
        return [new BlockTokenParser()];
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117 1
    public function getFilters()
118
    {
119 1
        return array(
120 1
            new TwigFilter('trans', function ($message) {
121 1
                return self::_($message);
122 1
            }),
123 1
        );
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129
    public function getName()
130
    {
131
        return 'PSFSi18n';
132
    }
133
134
    /**
135
     * @param $message
136
     * @param string $customKey
137
     * @param bool $forceReload
138
     * @return mixed|string
139
     */
140 10
    public static function _($message, $customKey = null, $forceReload = false)
141
    {
142 10
        if(0 === count(self::$translations) || $forceReload) {
143 1
            self::translationsCheckLoad($customKey, $forceReload);
144
        }
145 10
        if (is_array(self::$translations) && array_key_exists($message, self::$translations)) {
146 8
            $translation = self::$translations[$message];
147
        } else {
148 2
            $translation = gettext($message);
149
        }
150 10
        if (self::$generate) {
151
            self::generate($message, $translation);
152
        }
153 10
        return $translation;
154
    }
155
156
    /**
157
     * @param string $message
158
     * @param string $translation
159
     */
160
    protected static function generate($message, $translation)
161
    {
162
        if (!array_key_exists($message, self::$translations)) {
163
            self::$translations[$message] = $translation;
164
        }
165
        file_put_contents(self::$filename, json_encode(array_unique(self::$translations), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
166
    }
167
}
168