Issues (910)

framework/i18n/PhpMessageSource.php (1 issue)

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\i18n;
9
10
use Yii;
11
use yii\base\InvalidArgumentException;
12
13
/**
14
 * PhpMessageSource represents a message source that stores translated messages in PHP scripts.
15
 *
16
 * PhpMessageSource uses PHP arrays to keep message translations.
17
 *
18
 * - Each PHP script contains one array which stores the message translations in one particular
19
 *   language and for a single message category;
20
 * - Each PHP script is saved as a file named as "[[basePath]]/LanguageID/CategoryName.php";
21
 * - Within each PHP script, the message translations are returned as an array like the following:
22
 *
23
 * ```php
24
 * return [
25
 *     'original message 1' => 'translated message 1',
26
 *     'original message 2' => 'translated message 2',
27
 * ];
28
 * ```
29
 *
30
 * You may use [[fileMap]] to customize the association between category names and the file names.
31
 *
32
 * @author Qiang Xue <[email protected]>
33
 * @since 2.0
34
 */
35
class PhpMessageSource extends MessageSource
36
{
37
    /**
38
     * @var string the base path for all translated messages. Defaults to '@app/messages'.
39
     */
40
    public $basePath = '@app/messages';
41
    /**
42
     * @var array mapping between message categories and the corresponding message file paths.
43
     * The file paths are relative to [[basePath]]. For example,
44
     *
45
     * ```php
46
     * [
47
     *     'core' => 'core.php',
48
     *     'ext' => 'extensions.php',
49
     * ]
50
     * ```
51
     */
52
    public $fileMap;
53
54
55
    /**
56
     * Loads the message translation for the specified $language and $category.
57
     * If translation for specific locale code such as `en-US` isn't found it
58
     * tries more generic `en`. When both are present, the `en-US` messages will be merged
59
     * over `en`. See [[loadFallbackMessages]] for details.
60
     * If the $language is less specific than [[sourceLanguage]], the method will try to
61
     * load the messages for [[sourceLanguage]]. For example: [[sourceLanguage]] is `en-GB`,
62
     * $language is `en`. The method will load the messages for `en` and merge them over `en-GB`.
63
     *
64
     * @param string $category the message category
65
     * @param string $language the target language
66
     * @return array the loaded messages. The keys are original messages, and the values are the translated messages.
67
     * @see loadFallbackMessages
68
     * @see sourceLanguage
69
     */
70 174
    protected function loadMessages($category, $language)
71
    {
72 174
        $messageFile = $this->getMessageFilePath($category, $language);
73 174
        $messages = $this->loadMessagesFromFile($messageFile);
74
75 174
        $fallbackLanguage = substr((string)$language, 0, 2);
76 174
        $fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
77
78 174
        if ($fallbackLanguage !== '' && $language !== $fallbackLanguage) {
79 170
            $messages = $this->loadFallbackMessages($category, $fallbackLanguage, $messages, $messageFile);
80 8
        } elseif ($fallbackSourceLanguage !== '' && $language === $fallbackSourceLanguage) {
81 3
            $messages = $this->loadFallbackMessages($category, $this->sourceLanguage, $messages, $messageFile);
82 8
        } elseif ($messages === null) {
83 7
            Yii::warning("The message file for category '$category' does not exist: $messageFile", __METHOD__);
84
        }
85
86 174
        return (array) $messages;
87
    }
88
89
    /**
90
     * The method is normally called by [[loadMessages]] to load the fallback messages for the language.
91
     * Method tries to load the $category messages for the $fallbackLanguage and adds them to the $messages array.
92
     *
93
     * @param string $category the message category
94
     * @param string $fallbackLanguage the target fallback language
95
     * @param array $messages the array of previously loaded translation messages.
96
     * The keys are original messages, and the values are the translated messages.
97
     * @param string $originalMessageFile the path to the file with messages. Used to log an error message
98
     * in case when no translations were found.
99
     * @return array the loaded messages. The keys are original messages, and the values are the translated messages.
100
     * @since 2.0.7
101
     */
102 170
    protected function loadFallbackMessages($category, $fallbackLanguage, $messages, $originalMessageFile)
103
    {
104 170
        $fallbackMessageFile = $this->getMessageFilePath($category, $fallbackLanguage);
105 170
        $fallbackMessages = $this->loadMessagesFromFile($fallbackMessageFile);
106
107
        if (
108 170
            $messages === null && $fallbackMessages === null
109 170
            && $fallbackLanguage !== $this->sourceLanguage
110 170
            && strpos($this->sourceLanguage, $fallbackLanguage) !== 0
0 ignored issues
show
It seems like $this->sourceLanguage can also be of type null; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

110
            && strpos(/** @scrutinizer ignore-type */ $this->sourceLanguage, $fallbackLanguage) !== 0
Loading history...
111
        ) {
112 4
            Yii::error("The message file for category '$category' does not exist: $originalMessageFile "
113 4
                . "Fallback file does not exist as well: $fallbackMessageFile", __METHOD__);
114 170
        } elseif (empty($messages)) {
115 167
            return $fallbackMessages;
116 8
        } elseif (!empty($fallbackMessages)) {
117 8
            foreach ($fallbackMessages as $key => $value) {
118 8
                if (!empty($value) && empty($messages[$key])) {
119 8
                    $messages[$key] = $value;
120
                }
121
            }
122
        }
123
124 10
        return (array) $messages;
125
    }
126
127
    /**
128
     * Returns message file path for the specified language and category.
129
     *
130
     * @param string $category the message category
131
     * @param string $language the target language
132
     * @return string path to message file
133
     */
134 174
    protected function getMessageFilePath($category, $language)
135
    {
136 174
        $language = (string) $language;
137 174
        if ($language !== '' && !preg_match('/^[a-z0-9_-]+$/i', $language)) {
138
            throw new InvalidArgumentException(sprintf('Invalid language code: "%s".', $language));
139
        }
140 174
        $messageFile = Yii::getAlias($this->basePath) . "/$language/";
141 174
        if (isset($this->fileMap[$category])) {
142 4
            $messageFile .= $this->fileMap[$category];
143
        } else {
144 172
            $messageFile .= str_replace('\\', '/', $category) . '.php';
145
        }
146
147 174
        return $messageFile;
148
    }
149
150
    /**
151
     * Loads the message translation for the specified language and category or returns null if file doesn't exist.
152
     *
153
     * @param string $messageFile path to message file
154
     * @return array|null array of messages or null if file not found
155
     */
156 174
    protected function loadMessagesFromFile($messageFile)
157
    {
158 174
        if (is_file($messageFile)) {
159 169
            $messages = include $messageFile;
160 169
            if (!is_array($messages)) {
161
                $messages = [];
162
            }
163
164 169
            return $messages;
165
        }
166
167 170
        return null;
168
    }
169
}
170