Completed
Push — 11429-message-source ( f7ff15 )
by Dmitry
10:08
created

PhpMessageSource::loadMessagesFromFile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.1406
Metric Value
dl 0
loc 13
rs 9.4285
ccs 6
cts 8
cp 0.75
cc 3
eloc 8
nc 3
nop 1
crap 3.1406
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\i18n;
9
10
use Yii;
11
12
/**
13
 * PhpMessageSource represents a message source that stores translated messages in PHP scripts.
14
 *
15
 * PhpMessageSource uses PHP arrays to keep message translations.
16
 *
17
 * - Each PHP script contains one array which stores the message translations in one particular
18
 *   language and for a single message category;
19
 * - Each PHP script is saved as a file named as `[[basePath]]/LanguageID/CategoryName.php`;
20
 * - Within each PHP script, the message translations are returned as an array like the following:
21
 *
22
 * ```php
23
 * return [
24
 *     'original message 1' => 'translated message 1',
25
 *     'original message 2' => 'translated message 2',
26
 * ];
27
 * ```
28
 *
29
 * You may use [[fileMap]] to customize the association between category names and the file names.
30
 *
31
 * @author Qiang Xue <[email protected]>
32
 * @since 2.0
33
 */
34
class PhpMessageSource extends MessageSource
35
{
36
    /**
37
     * @var string the base path for all translated messages. Defaults to '@app/messages'.
38
     */
39
    public $basePath = '@app/messages';
40
    /**
41
     * @var array mapping between message categories and the corresponding message file paths.
42
     * The file paths are relative to [[basePath]]. For example,
43
     *
44
     * ```php
45
     * [
46
     *     'core' => 'core.php',
47
     *     'ext' => 'extensions.php',
48
     * ]
49
     * ```
50
     */
51
    public $fileMap;
52
53
54
    /**
55
     * Loads the message translation for the specified $language and $category.
56
     * If translation for specific locale code such as `en-US` isn't found it
57
     * tries more generic `en`. When both are present, the `en-US` messages will be merged
58
     * over `en`. See [[loadFallbackMessages]] for details.
59
     * If the $language is less specific than [[sourceLanguage]], the method will try to
60
     * load the messages for [[sourceLanguage]]. For example: [[sourceLanguage]] is `en-GB`,
61
     * $language is `en`. The method will load the messages for `en` and merge them over `en-GB`.
62
     *
63
     * @param string $category the message category
64
     * @param string $language the target language
65
     * @return array the loaded messages. The keys are original messages, and the values are the translated messages.
66
     * @see loadFallbackMessages
67
     * @see sourceLanguage
68
     */
69 161
    protected function loadMessages($category, $language)
70
    {
71 161
        $messageFile = $this->getMessageFilePath($category, $language);
72 161
        $messages = $this->loadMessagesFromFile($messageFile);
73
74 161
        $fallbackLanguage = substr($language, 0, 2);
75 161
        $fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
76
77 161
        if ($language !== $fallbackLanguage) {
78 157
            $messages = $this->loadFallbackMessages($category, $fallbackLanguage, $messages, $messageFile);
0 ignored issues
show
Bug introduced by
It seems like $messages defined by $this->loadFallbackMessa...messages, $messageFile) on line 78 can also be of type null; however, yii\i18n\PhpMessageSource::loadFallbackMessages() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
79 161
        } elseif ($language === $fallbackSourceLanguage) {
80 3
            $messages = $this->loadFallbackMessages($category, $this->sourceLanguage, $messages, $messageFile);
0 ignored issues
show
Bug introduced by
It seems like $messages defined by $this->loadFallbackMessa...messages, $messageFile) on line 80 can also be of type null; however, yii\i18n\PhpMessageSource::loadFallbackMessages() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
81 3
        } else {
82 8
            if ($messages === null) {
83 5
                Yii::error("The message file for category '$category' does not exist: $messageFile", __METHOD__);
84 5
            }
85
        }
86
87 161
        return (array) $messages;
88
    }
89
90
    /**
91
     * The method is normally called by [[loadMessages]] to load the fallback messages for the language.
92
     * Method tries to load the $category messages for the $fallbackLanguage and adds them to the $messages array.
93
     *
94
     * @param string $category the message category
95
     * @param string $fallbackLanguage the target fallback language
96
     * @param array $messages the array of previously loaded translation messages.
97
     * The keys are original messages, and the values are the translated messages.
98
     * @param string $originalMessageFile the path to the file with messages. Used to log an error message
99
     * in case when no translations were found.
100
     * @return array the loaded messages. The keys are original messages, and the values are the translated messages.
101
     * @since 2.0.7
102
     */
103 157
    protected function loadFallbackMessages($category, $fallbackLanguage, $messages, $originalMessageFile)
104
    {
105 157
        $fallbackMessageFile = $this->getMessageFilePath($category, $fallbackLanguage);
106 157
        $fallbackMessages = $this->loadMessagesFromFile($fallbackMessageFile);
107
108
        if (
109 157
            $messages === null && $fallbackMessages === null 
110 157
            && $fallbackLanguage !== $this->sourceLanguage
111 157
            && $fallbackLanguage !== substr($this->sourceLanguage, 0, 2)
112 157
        ) {
113 4
            Yii::error("The message file for category '$category' does not exist: $originalMessageFile "
114 4
                . "Fallback file does not exist as well: $fallbackMessageFile", __METHOD__);
115 157
        } elseif (empty($messages)) {
116 154
            return $fallbackMessages;
117 8
        } elseif (!empty($fallbackMessages)) {
118 8
            foreach ($fallbackMessages as $key => $value) {
119 8
                if (!empty($value) && empty($messages[$key])) {
120 8
                    $messages[$key] = $fallbackMessages[$key];
121 8
                }
122 8
            }
123 8
        }
124
125 10
        return (array) $messages;
126
    }
127
128
    /**
129
     * Returns message file path for the specified language and category.
130
     *
131
     * @param string $category the message category
132
     * @param string $language the target language
133
     * @return string path to message file
134
     */
135 161
    protected function getMessageFilePath($category, $language)
136
    {
137 161
        $messageFile = Yii::getAlias($this->basePath) . "/$language/";
138 161
        if (isset($this->fileMap[$category])) {
139 4
            $messageFile .= $this->fileMap[$category];
140 4
        } else {
141 159
            $messageFile .= str_replace('\\', '/', $category) . '.php';
142
        }
143
144 161
        return $messageFile;
145
    }
146
147
    /**
148
     * Loads the message translation for the specified language and category or returns null if file doesn't exist.
149
     *
150
     * @param string $messageFile path to message file
151
     * @return array|null array of messages or null if file not found
152
     */
153 161
    protected function loadMessagesFromFile($messageFile)
154
    {
155 161
        if (is_file($messageFile)) {
156 156
            $messages = include($messageFile);
157 156
            if (!is_array($messages)) {
158
                $messages = [];
159
            }
160
161 156
            return $messages;
162
        } else {
163 157
            return null;
164
        }
165
    }
166
}
167