Completed
Push — master ( 56c695...dbb523 )
by Michal
03:48
created

Translator::extractPluralCount()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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