Passed
Push — master ( 92142b...f1013d )
by William
11:25
created

Translator::loadTranslationsFromFile()   B

Complexity

Conditions 6
Paths 24

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 25
c 0
b 0
f 0
dl 0
loc 41
rs 8.8977
ccs 21
cts 21
cp 1
cc 6
nc 24
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
    Copyright (c) 2003, 2009 Danilo Segan <[email protected]>.
7
    Copyright (c) 2005 Nico Kaiser <[email protected]>
8
    Copyright (c) 2016 Michal Čihař <[email protected]>
9
10
    This file is part of MoTranslator.
11
12
    This program is free software; you can redistribute it and/or modify
13
    it under the terms of the GNU General Public License as published by
14
    the Free Software Foundation; either version 2 of the License, or
15
    (at your option) any later version.
16
17
    This program is distributed in the hope that it will be useful,
18
    but WITHOUT ANY WARRANTY; without even the implied warranty of
19
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
    GNU General Public License for more details.
21
22
    You should have received a copy of the GNU General Public License along
23
    with this program; if not, write to the Free Software Foundation, Inc.,
24
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25
*/
26
27
namespace PhpMyAdmin\MoTranslator;
28
29
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
30
use Throwable;
31
use function array_key_exists;
32
use function chr;
33
use function count;
34
use function explode;
35
use function implode;
36
use function intval;
37
use function is_readable;
38
use function ltrim;
39
use function preg_replace;
40
use function rtrim;
41
use function strcmp;
42
use function stripos;
43
use function strpos;
44
use function strtolower;
45
use function substr;
46
use function trim;
47
48
/**
49
 * Provides a simple gettext replacement that works independently from
50
 * the system's gettext abilities.
51
 * It can read MO files and use them for translating strings.
52
 *
53
 * It caches ll strings and translations to speed up the string lookup.
54
 */
55
class Translator
56
{
57
    /**
58
     * None error.
59
     */
60
    public const ERROR_NONE = 0;
61
    /**
62
     * File does not exist.
63
     */
64
    public const ERROR_DOES_NOT_EXIST = 1;
65
    /**
66
     * File has bad magic number.
67
     */
68
    public const ERROR_BAD_MAGIC = 2;
69
    /**
70
     * Error while reading file, probably too short.
71
     */
72
    public const ERROR_READING = 3;
73
74
    /**
75
     * Big endian mo file magic bytes.
76
     */
77
    public const MAGIC_BE = "\x95\x04\x12\xde";
78
    /**
79
     * Little endian mo file magic bytes.
80
     */
81
    public const MAGIC_LE = "\xde\x12\x04\x95";
82
83
    /**
84
     * Parse error code (0 if no error).
85
     *
86
     * @var int
87
     */
88
    public $error = self::ERROR_NONE;
89
90
    /**
91
     * Cache header field for plural forms.
92
     *
93
     * @var string|null
94
     */
95
    private $pluralEquation = null;
96
97
    /** @var ExpressionLanguage|null Evaluator for plurals */
98
    private $pluralExpression = null;
99
100
    /** @var int|null number of plurals */
101
    private $pluralCount = null;
102
103
    /**
104
     * Array with original -> translation mapping.
105
     *
106
     * @var array<string,string>
107
     */
108
    private $cacheTranslations = [];
109
110
    /**
111
     * @param string $filename Name of mo file to load
112 180
     */
113
    public function __construct(string $filename)
114 180
    {
115 24
        $this->loadTranslationsFromFile($filename);
116
    }
117 24
118
    /**
119
     * Load a Mo file translations
120 156
     *
121
     * @param string $filename Name of mo file to load
122
     */
123 156
    private function loadTranslationsFromFile(string $filename): void
124 152
    {
125 120
        if (! is_readable($filename)) {
126 32
            $this->error = self::ERROR_DOES_NOT_EXIST;
127 28
128
            return;
129 4
        }
130
131 4
        $stream = new StringReader($filename);
132
133
        try {
134
            $magic = $stream->read(0, 4);
135 148
            if (strcmp($magic, self::MAGIC_LE) === 0) {
136 148
                $unpack = 'V';
137 136
            } elseif (strcmp($magic, self::MAGIC_BE) === 0) {
138
                $unpack = 'N';
139
            } else {
140 136
                $this->error = self::ERROR_BAD_MAGIC;
141 132
142
                return;
143
            }
144 132
145 132
            /* Parse header */
146 132
            $total = $stream->readint($unpack, 8);
147 132
            $originals = $stream->readint($unpack, 12);
148
            $translations = $stream->readint($unpack, 16);
149 20
150 20
            /* get original and translations tables */
151
            $tableOriginals = $stream->readintarray($unpack, $originals, $total * 2);
152 20
            $tableTranslations = $stream->readintarray($unpack, $translations, $total * 2);
153
154 132
            /* read all strings to the cache */
155
            for ($i = 0; $i < $total; ++$i) {
156
                $original = $stream->read($tableOriginals[$i * 2 + 2], $tableOriginals[$i * 2 + 1]);
157
                $translation = $stream->read($tableTranslations[$i * 2 + 2], $tableTranslations[$i * 2 + 1]);
158
                $this->cacheTranslations[$original] = $translation;
159
            }
160
        } catch (ReaderException $e) {
161
            $this->error = self::ERROR_READING;
162
163 120
            return;
164
        }
165 120
    }
166 84
167
    /**
168
     * Translates a string.
169 60
     *
170
     * @param string $msgid String to be translated
171
     *
172
     * @return string translated string (or original, if not found)
173
     */
174
    public function gettext(string $msgid): string
175
    {
176
        if (array_key_exists($msgid, $this->cacheTranslations)) {
177 24
            return $this->cacheTranslations[$msgid];
178
        }
179 24
180
        return $msgid;
181
    }
182
183
    /**
184
     * Check if a string is translated.
185
     *
186
     * @param string $msgid String to be checked
187
     */
188
    public function exists(string $msgid): bool
189 56
    {
190
        return array_key_exists($msgid, $this->cacheTranslations);
191
    }
192 56
193 56
    /**
194 44
     * Sanitize plural form expression for use in ExpressionLanguage.
195
     *
196 12
     * @param string $expr Expression to sanitize
197
     *
198
     * @return string sanitized plural form expression
199 56
     */
200
    public static function sanitizePluralExpression(string $expr): string
201 56
    {
202 48
        // Parse equation
203
        $expr = explode(';', $expr);
204
        if (count($expr) >= 2) {
205
            $expr = $expr[1];
206 56
        } else {
207 48
            $expr = $expr[0];
208
        }
209
210
        $expr = trim(strtolower($expr));
211 56
        // Strip plural prefix
212
        if (substr($expr, 0, 6) === 'plural') {
213 56
            $expr = ltrim(substr($expr, 6));
214
        }
215
216
        // Strip equals
217
        if (substr($expr, 0, 1) === '=') {
218
            $expr = ltrim(substr($expr, 1));
219
        }
220
221
        // Cleanup from unwanted chars
222
        $expr = preg_replace('@[^n0-9:\(\)\?=!<>/%&| ]@', '', $expr);
223 52
224
        return (string) $expr;
225 52
    }
226 52
227 52
    /**
228 8
     * Extracts number of plurals from plurals form expression.
229
     *
230
     * @param string $expr Expression to process
231 44
     *
232 4
     * @return int Total number of plurals
233
     */
234
    public static function extractPluralCount(string $expr): int
235 40
    {
236
        $parts = explode(';', $expr, 2);
237
        $nplurals = explode('=', trim($parts[0]), 2);
238
        if (strtolower(rtrim($nplurals[0])) !== 'nplurals') {
239
            return 1;
240
        }
241
242
        if (count($nplurals) === 1) {
243
            return 1;
244
        }
245 44
246
        return intval($nplurals[1]);
247 44
    }
248 44
249 44
    /**
250 44
     * Parse full PO header and extract only plural forms line.
251 44
     *
252
     * @param string $header Gettext header
253
     *
254 28
     * @return string verbatim plural form header field
255
     */
256
    public static function extractPluralsForms(string $header): string
257 44
    {
258
        $headers = explode("\n", $header);
259
        $expr = 'nplurals=2; plural=n == 1 ? 0 : 1;';
260
        foreach ($headers as $header) {
261
            if (stripos($header, 'Plural-Forms:') !== 0) {
262
                continue;
263
            }
264
265 32
            $expr = substr($header, 13);
266
        }
267
268
        return $expr;
269
    }
270
271 32
    /**
272 28
     * Get possible plural forms from MO header.
273 20
     *
274
     * @return string plural form header
275 8
     */
276
    private function getPluralForms(): string
277
    {
278 28
        // lets assume message number 0 is header
279 28
        // this is true, right?
280 28
281
        // cache header field for plural forms
282
        if ($this->pluralEquation === null) {
283 32
            if (isset($this->cacheTranslations[''])) {
284
                $header = $this->cacheTranslations[''];
285
            } else {
286
                $header = '';
287
            }
288
289
            $expr = $this->extractPluralsForms($header);
290
            $this->pluralEquation = $this->sanitizePluralExpression($expr);
291
            $this->pluralCount = $this->extractPluralCount($expr);
292
        }
293 32
294
        return $this->pluralEquation;
295 32
    }
296 28
297
    /**
298
     * Detects which plural form to take.
299
     *
300 32
     * @param int $n count of objects
301 32
     *
302 32
     * @return int array index of the right plural form
303
     */
304 4
    private function selectString(int $n): int
305 4
    {
306
        if ($this->pluralExpression === null) {
307
            $this->pluralExpression = new ExpressionLanguage();
308 32
        }
309 4
310
        try {
311
            $plural = $this->pluralExpression->evaluate(
312 32
                $this->getPluralForms(),
313
                ['n' => $n]
314
            );
315
        } catch (Throwable $e) {
316
            $plural = 0;
317
        }
318
319
        if ($plural >= $this->pluralCount) {
320
            $plural = $this->pluralCount - 1;
321
        }
322
323
        return $plural;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $plural could return the type array which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
324 72
    }
325
326
    /**
327 72
     * Plural version of gettext.
328 72
     *
329 72
     * @param string $msgid       Single form
330
     * @param string $msgidPlural Plural form
331
     * @param int    $number      Number of objects
332
     *
333 32
     * @return string translated plural form
334
     */
335 32
    public function ngettext(string $msgid, string $msgidPlural, int $number): string
336 32
    {
337 32
        // this should contains all strings separated by NULLs
338
        $key = implode(chr(0), [$msgid, $msgidPlural]);
339
        if (! array_key_exists($key, $this->cacheTranslations)) {
340
            return $number !== 1 ? $msgidPlural : $msgid;
341 32
        }
342 4
343
        // find out the appropriate form
344
        $select = $this->selectString($number);
345 32
346
        $result = $this->cacheTranslations[$key];
347
        $list = explode(chr(0), $result);
348
        if ($list === false) {
349
            return '';
350
        }
351
352
        if (! isset($list[$select])) {
353
            return $list[0];
354
        }
355
356 56
        return $list[$select];
357
    }
358 56
359 56
    /**
360 56
     * Translate with context.
361 24
     *
362
     * @param string $msgctxt Context
363
     * @param string $msgid   String to be translated
364 32
     *
365
     * @return string translated plural form
366
     */
367
    public function pgettext(string $msgctxt, string $msgid): string
368
    {
369
        $key = implode(chr(4), [$msgctxt, $msgid]);
370
        $ret = $this->gettext($key);
371
        if (strpos($ret, chr(4)) !== false) {
372
            return $msgid;
373
        }
374
375
        return $ret;
376
    }
377 16
378
    /**
379 16
     * Plural version of pgettext.
380 16
     *
381 16
     * @param string $msgctxt     Context
382 4
     * @param string $msgid       Single form
383
     * @param string $msgidPlural Plural form
384
     * @param int    $number      Number of objects
385 12
     *
386
     * @return string translated plural form
387
     */
388
    public function npgettext(string $msgctxt, string $msgid, string $msgidPlural, int $number): string
389
    {
390
        $key = implode(chr(4), [$msgctxt, $msgid]);
391
        $ret = $this->ngettext($key, $msgidPlural, $number);
392
        if (strpos($ret, chr(4)) !== false) {
393
            return $msgid;
394 4
        }
395
396 4
        return $ret;
397 4
    }
398
399
    /**
400
     * Set translation in place
401
     *
402
     * @param string $msgid  String to be set
403
     * @param string $msgstr Translation
404
     */
405
    public function setTranslation(string $msgid, string $msgstr): void
406
    {
407
        $this->cacheTranslations[$msgid] = $msgstr;
408
    }
409
}
410