Test Failed
Push — main ( 330702...6ea9a3 )
by Rafael
14:31
created

Trans::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
/* Copyright (C) 2024      Rafael San José      <[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
namespace Alxarafe\Lib;
20
21
use Alxarafe\Tools\Debug;
22
use DebugBar\DebugBar;
23
use Symfony\Component\Translation\Translator;
24
use Symfony\Component\Translation\Loader\ArrayLoader;
25
use Symfony\Component\Yaml\Yaml;
26
27
abstract class Trans
28
{
29
    /**
30
     * It is the default language when none has been specified yet.
31
     */
32
    public const FALLBACK_LANG = 'en';
33
34
    private static $translator;
35
36
    private static $translations = [];
37
38
    /**
39
     * List of strings without translation, for debugging bar purposes.
40
     *
41
     * @var array
42
     */
43
    private static $missingStrings = [];
44
45
    private static $missingStringsDebug;
46
47
    /**
48
     * Initializes the translator.
49
     *
50
     * @return bool
51
     */
52
    public static function initialize()
53
    {
54
        if (isset(self::$translator)) {
55
            return true;
56
        }
57
58
        self::$translator = new Translator(self::FALLBACK_LANG);
59
        return isset(self::$translator);
60
    }
61
62
    public static function getMissingStrings()
63
    {
64
        self::$missingStringsDebug = [];
65
        $locale = self::$translator->getLocale();
66
        foreach (self::$missingStrings as $name => $value) {
67
            if ($value['lang'] === $locale) {
68
                continue;
69
            }
70
            self::$missingStringsDebug[$name] = '(' . $value['lang'] . ') ' . $value['text'];
71
        }
72
        return self::$missingStringsDebug;
73
    }
74
75
    /**
76
     * Return a text in the selected language.
77
     *
78
     * @param string $message
79
     * @param array $parameters
80
     * @param string|null $locale
81
     * @return string
82
     */
83
    public static function _(string $message, array $parameters = [], ?string $locale = null): string
84
    {
85
        if (!isset($locale)) {
86
            $locale = self::$translator->getLocale();
87
        }
88
89
        $params = [];
90
        foreach ($parameters as $name => $value) {
91
            $params['%' . $name . '%'] = $value;
92
        }
93
94
        if (!isset(self::$translations[$message])) {
95
            self::$missingStrings[$message] = [
96
                'lang' => self::FALLBACK_LANG,
97
                'text' => 'Not defined!',
98
            ];
99
        }
100
101
        return self::$translator->trans($message, $params, null, $locale);
102
    }
103
104
    private static function getTranslations($lang)
105
    {
106
        if (empty(self::$translations)) {
107
            $module = $_GET['module'];
108
            $main_route = realpath(constant('BASE_PATH') . '/../vendor/rsanjoseo/alxarafe/src');
109
            $routes = [
110
                $main_route . '/Lang',
111
                $main_route . '/Modules/' . $module . '/Lang',
112
            ];
113
114
            self::$translator->addLoader('array', new ArrayLoader());
115
            foreach ($routes as $route) {
116
                if ($lang !== self::FALLBACK_LANG) {
117
                    self::loadLang(self::FALLBACK_LANG, $route);
118
                }
119
                self::loadLang($lang, $route);
120
            }
121
122
            self::$translator->addResource('array', self::$translations, $lang);
123
        }
124
    }
125
126
    /**
127
     * Loads language files for the specified path and language.
128
     *
129
     * @param string $lang
130
     * @param string $folder
131
     */
132
    private static function loadLang(string $lang, string $folder): void
133
    {
134
        if (strlen($lang) > 2) {
135
            self::loadLang(substr($lang, 0, 2), $folder);
136
        }
137
138
        $filename = $folder . '/' . $lang . '.yaml';
139
        if (!file_exists($filename)) {
140
            Debug::message($filename . ' not found');
141
            return;
142
        }
143
144
        $translates = Yaml::parseFile($filename);
145
        if (!is_array($translates)) {
146
            Debug::message($filename . ' is not a valid YAML file');
147
            return;
148
        }
149
150
        foreach ($translates as $name => $translate) {
151
            self::$translations[$name] = $translate;
152
            self::$missingStrings[$name] = [
153
                'lang' => $lang,
154
                'text' => $translate
155
            ];
156
        }
157
    }
158
159
    /**
160
     * Return a text in the selected language.
161
     * Call directly to extra short function _
162
     *
163
     * @param $message
164
     * @param array $parameters
165
     * @param $locale
166
     * @return mixed
167
     */
168
    public static function trans($message, array $parameters = [], $locale = null)
169
    {
170
        return self::_($message, $parameters, $locale);
171
    }
172
173
    /**
174
     * Loads core and module lang files
175
     *
176
     * @param $lang
177
     * @return void
178
     */
179
    public static function setLang($lang)
180
    {
181
        self::$translator->setLocale($lang);
182
        self::getTranslations($lang);
183
    }
184
}
185