GettextTranslator::localeChanged()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace Agavi\Translation;
3
4
// +---------------------------------------------------------------------------+
5
// | This file is part of the Agavi package.                                   |
6
// | Copyright (c) 2005-2011 the Agavi Project.                                |
7
// |                                                                           |
8
// | For the full copyright and license information, please view the LICENSE   |
9
// | file that was distributed with this source code. You can also view the    |
10
// | LICENSE file online at http://www.agavi.org/LICENSE.txt                   |
11
// |   vi: set noexpandtab:                                                    |
12
// |   Local Variables:                                                        |
13
// |   indent-tabs-mode: t                                                     |
14
// |   End:                                                                    |
15
// +---------------------------------------------------------------------------+
16
use Agavi\Core\Context;
17
use Agavi\Exception\AgaviException;
18
use Agavi\Translation\Gettext\GettextMoReader;
19
use Agavi\Util\Toolkit;
20
21
/**
22
 * GettextTranslator defines the translator interface for gettext.
23
 *
24
 * @package    agavi
25
 * @subpackage translation
26
 *
27
 * @author     Dominik del Bondio <[email protected]>
28
 * @copyright  Authors
29
 * @copyright  The Agavi Project
30
 *
31
 * @since      0.11.0
32
 *
33
 * @version    $Id$
34
 */
35
class GettextTranslator extends BasicTranslator
36
{
37
    /**
38
     * @var        string A pattern for the path to the domain files.
39
     */
40
    protected $domainPathPattern = null;
41
42
    /**
43
     * @var        array The paths to the locale files indexed by domains
44
     */
45
    protected $domainPaths = array();
46
47
    /**
48
     * @var        array The data for each domain
49
     */
50
    protected $domainData = array();
51
    
52
    /**
53
     * @var        string The locale identifier of the current locale
54
     */
55
    protected $locale = null;
56
57
    /**
58
     * @var        string The name of the plural form function
59
     */
60
    protected $pluralFormFunc = null;
61
    
62
    /**
63
     * @var        bool Whether or not to write a file with all used translations
64
     *                  that can be parsed using xgettext.
65
     */
66
    protected $storeTranslationCalls = false;
67
    
68
    /**
69
     * @var        string The folder to write translation call files to.
70
     */
71
    protected $translationCallStoreDir = null;
72
73
    /**
74
     * Initialize this Translator.
75
     *
76
     * @param      Context $context The current application context.
77
     * @param      array   $parameters An associative array of initialization parameters
78
     *
79
     * @author     Dominik del Bondio <[email protected]>
80
     * @since      0.11.0
81
     */
82
    public function initialize(Context $context, array $parameters = array())
83
    {
84
        parent::initialize($context);
85
86
        if (isset($parameters['text_domains']) && is_array($parameters['text_domains'])) {
87
            foreach ($parameters['text_domains'] as $domain => $path) {
88
                $this->domainPaths[$domain] = $path;
89
            }
90
        }
91
92
        if (isset($parameters['text_domain_pattern'])) {
93
            $this->domainPathPattern = $parameters['text_domain_pattern'];
94
        }
95
        
96
        if (isset($parameters['store_calls'])) {
97
            $this->storeTranslationCalls = true;
98
            $this->translationCallStoreDir = $parameters['store_calls'];
99
            Toolkit::mkdir($parameters['store_calls'], 0777, true);
100
        }
101
    }
102
103
    /**
104
     * Translates a message into the defined language.
105
     *
106
     * @param      mixed       $message The message to be translated.
107
     * @param      string      $domain The domain of the message.
108
     * @param      Locale $locale The locale to which the message should be
109
     *                         translated.
110
     *
111
     * @return     string The translated message.
112
     *
113
     * @author     Dominik del Bondio <[email protected]>
114
     * @since      0.11.0
115
     */
116
    public function translate($message, $domain, Locale $locale = null)
117
    {
118
        if ($locale) {
119
            $oldDomainData = $this->domainData;
120
            $oldLocale = $this->locale;
121
            $this->localeChanged($locale);
0 ignored issues
show
Documentation introduced by
$locale is of type object<Agavi\Translation\Locale>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
122
        }
123
124
        // load domain data from file
125
        if (!isset($this->domainData[$domain])) {
126
            $this->loadDomainData($domain);
127
        }
128
129
        if (is_array($message)) {
130
            $singularMsg = $message[0];
131
            $pluralMsg = $message[1];
132
            $count = $message[2];
133
            if ($this->pluralFormFunc) {
134
                $funcName = $this->pluralFormFunc;
135
                $msgId = (int) $funcName($count);
136
            } else {
137
                $msgId = ($count == 1) ? 0 : 1;
138
            }
139
140
            $msgKey = $singularMsg . chr(0) . $pluralMsg;
141
142
            if (isset($this->domainData[$domain]['msgs'][$msgKey])) {
143
                $pluralMsgs = explode(chr(0), $this->domainData[$domain]['msgs'][$msgKey]);
144
                $data = $pluralMsgs[$msgId];
145
            } else {
146
                $data = ($msgId == 0) ? $singularMsg : $pluralMsg;
147
            }
148
        } else {
149
            $data = isset($this->domainData[$domain]['msgs'][$message]) ? $this->domainData[$domain]['msgs'][$message] : $message;
150
        }
151
152
        // in "devel" mode, write a gettext() or ngettext() call to a file for xgettext parsing
153
        if ($this->storeTranslationCalls) {
154
            file_put_contents(
155
                $this->translationCallStoreDir . DIRECTORY_SEPARATOR . $domain . '.php',
156
                "" . (is_array($message) ?
157
                    ('ngettext(' . var_export($message[0], true) . ', ' . var_export($message[1], true) . ', ' . var_export($message[2], true) . ')') :
158
                    ('gettext(' . var_export($message, true) . ')')
159
                ) . ";\n",
160
            FILE_APPEND);
161
        }
162
163
        if ($locale) {
164
            $this->domainData = $oldDomainData;
0 ignored issues
show
Bug introduced by
The variable $oldDomainData does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
165
            $this->locale = $oldLocale;
0 ignored issues
show
Bug introduced by
The variable $oldLocale does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
166
        }
167
168
        return $data;
169
    }
170
171
    /**
172
     * This method gets called by the translation manager when the default locale
173
     * has been changed.
174
     *
175
     * @param      string $newLocale The new default locale.
176
     *
177
     * @author     Dominik del Bondio <[email protected]>
178
     * @since      0.11.0
179
     */
180
    public function localeChanged($newLocale)
181
    {
182
        $this->locale = $newLocale;
183
        $this->domainData = array();
184
        $this->pluralFormFunc = null;
185
    }
186
187
    /**
188
     * Loads the data from the data file for the given domain with the current
189
     * locale.
190
     *
191
     * @param      string $domain The domain to load the data for.
192
     *
193
     * @author     Dominik del Bondio <[email protected]>
194
     * @since      0.11.0
195
     */
196
    public function loadDomainData($domain)
197
    {
198
        $localeName = $this->locale->getIdentifier();
0 ignored issues
show
Bug introduced by
The method getIdentifier cannot be called on $this->locale (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
199
        $localeNameBases = Locale::getLookupPath($localeName);
200
201
        if (!isset($this->domainPaths[$domain])) {
202
            if (!$this->domainPathPattern) {
203
                throw new AgaviException('Using domain "' . $domain . '" which has no path specified');
204
            } else {
205
                $basePath = $this->domainPathPattern;
206
            }
207
        } else {
208
            $basePath = $this->domainPaths[$domain];
209
        }
210
211
        $basePath = Toolkit::expandVariables($basePath, array('domain' => $domain));
212
213
        $data = array();
214
215
        foreach ($localeNameBases as $localeNameBase) {
216
            $fileName = Toolkit::expandVariables($basePath, array('locale' => $localeNameBase));
217
            if ($fileName === $basePath) {
218
                // no replacing of $locale happened
219
                $fileName = $basePath . '/' . $localeNameBase . '.mo';
220
            }
221
            if (is_readable($fileName)) {
222
                $fileData = GettextMoReader::readFile($fileName);
223
                
224
                // instead of array_merge, which doesn't handle null bytes in keys properly. careful, the order matters here.
225
                $data = $fileData + $data;
226
            }
227
        }
228
229
        $headers = array();
230
231
        if (count($data)) {
232
            $headerData = str_replace("\r", '', $data['']);
233
            $headerLines = explode("\n", $headerData);
234
            foreach ($headerLines as $line) {
235
                $values = explode(':', $line, 2);
236
                // skip empty / invalid lines
237
                if (count($values) == 2) {
238
                    $headers[$values[0]] = $values[1];
239
                }
240
            }
241
        }
242
243
        $this->pluralFormFunc = null;
244
        if (isset($headers['Plural-Forms'])) {
245
            $pf = $headers['Plural-Forms'];
246
            if (preg_match('#nplurals=\d+;\s+plural=(.*)$#D', $pf, $match)) {
247
                $funcCode = $match[1];
248
                $validOpChars = array(' ', 'n', '!', '&', '|', '<', '>', '(', ')', '?', ':', ';', '=', '+', '*', '/', '%', '-');
249
                if (preg_match('#[^\d' . preg_quote(implode('', $validOpChars), '#') . ']#', $funcCode, $errorMatch)) {
250
                    throw new AgaviException('Illegal character ' . $errorMatch[0] . ' in plural form ' . $funcCode);
251
                }
252
                
253
                // add parenthesis around all ternary expressions. This is done
254
                // to make the ternary operator (?) have precedence over the delimiter (:)
255
                // This will transform
256
                // "a ? 1 : b ? c ? 3 : 4 : 2" to "(a ? 1 : (b ? (c ? 3 : 4) : 2))" and
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
257
                // "a ? b ? c ? d ? 5 : 4 : 3 : 2 : 1" to "(a ? (b ? (c ? (d ? 5 : 4) : 3) : 2) : 1)"
258
                // "a ? b ? c ? 4 : 3 : d ? 5 : 2 : 1" to "(a ? (b ? (c ? 4 : 3) : (d ? 5 : 2)) : 1)"
259
                // "a ? b ? c ? 4 : 3 : d ? 5 : e ? 6 : 2 : 1" to "(a ? (b ? (c ? 4 : 3) : (d ? 5 : (e ? 6 : 2))) : 1)"
260
                
261
                $funcCode = rtrim($funcCode, ';');
262
                $parts = preg_split('#(\?|\:)#', $funcCode, -1, PREG_SPLIT_DELIM_CAPTURE);
263
                $parenthesisCount = 0;
264
                $unclosedParenthesisCount = 0;
265
                $firstParenthesis = true;
0 ignored issues
show
Unused Code introduced by
$firstParenthesis is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
266
                $funcCode = '';
267
                for ($i = 0, $c = count($parts); $i < $c; ++$i) {
268
                    $lastPart = $i > 0 ? $parts[$i - 1] : null;
269
                    $part = $parts[$i];
270
                    $nextPart = $i + 1 < $c ? $parts[$i + 1] : null;
271
                    if ($nextPart == '?') {
272
                        if ($lastPart == ':') {
273
                            // keep track of parenthesis which need to be closed
274
                            // directly after this ternary expression
275
                            ++$unclosedParenthesisCount;
276
                            --$parenthesisCount;
277
                        }
278
                        $funcCode .= ' (' . $part;
279
                        ++$parenthesisCount;
280
                    } elseif ($lastPart == ':') {
281
                        $funcCode .= $part . ') ';
282
                        if ($unclosedParenthesisCount > 0) {
283
                            $funcCode .= str_repeat(')', $unclosedParenthesisCount);
284
                            $unclosedParenthesisCount = 0;
285
                        }
286
                        --$parenthesisCount;
287
                    } else {
288
                        $funcCode .= $part;
289
                    }
290
                }
291
                if ($parenthesisCount > 0) {
292
                    // add the missing top level parenthesis
293
                    $funcCode .= str_repeat(')', $parenthesisCount);
294
                }
295
                $funcCode .= ';';
296
                $funcCode = 'return ' . str_replace('n', '$n', $funcCode);
297
                $this->pluralFormFunc = create_function('$n', $funcCode);
0 ignored issues
show
Security Best Practice introduced by
The use of create_function is highly discouraged, better use a closure.

create_function can pose a great security vulnerability as it is similar to eval, and could be used for arbitrary code execution. We highly recommend to use a closure instead.

// Instead of
$function = create_function('$a, $b', 'return $a + $b');

// Better use
$function = function($a, $b) { return $a + $b; }
Loading history...
298
            }
299
        }
300
301
        $this->domainData[$domain] = array('headers' => $headers, 'msgs' => $data);
302
    }
303
}
304