yii2

Форк
1
/
MessageSource.php 
125 строк · 4.4 Кб
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\Component;
12

13
/**
14
 * MessageSource is the base class for message translation repository classes.
15
 *
16
 * A message source stores message translations in some persistent storage.
17
 *
18
 * Child classes should override [[loadMessages()]] to provide translated messages.
19
 *
20
 * @author Qiang Xue <qiang.xue@gmail.com>
21
 * @since 2.0
22
 */
23
class MessageSource extends Component
24
{
25
    /**
26
     * @event MissingTranslationEvent an event that is triggered when a message translation is not found.
27
     */
28
    const EVENT_MISSING_TRANSLATION = 'missingTranslation';
29

30
    /**
31
     * @var bool whether to force message translation when the source and target languages are the same.
32
     * Defaults to false, meaning translation is only performed when source and target languages are different.
33
     */
34
    public $forceTranslation = false;
35
    /**
36
     * @var string|null the language that the original messages are in. If not set, it will use the value of
37
     * [[\yii\base\Application::sourceLanguage]].
38
     */
39
    public $sourceLanguage;
40

41
    private $_messages = [];
42

43

44
    /**
45
     * Initializes this component.
46
     */
47
    public function init()
48
    {
49
        parent::init();
50
        if ($this->sourceLanguage === null) {
51
            $this->sourceLanguage = Yii::$app->sourceLanguage;
52
        }
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`.
59
     *
60
     * @param string $category the message category
61
     * @param string $language the target language
62
     * @return array the loaded messages. The keys are original messages, and the values
63
     * are translated messages.
64
     */
65
    protected function loadMessages($category, $language)
66
    {
67
        return [];
68
    }
69

70
    /**
71
     * Translates a message to the specified language.
72
     *
73
     * Note that unless [[forceTranslation]] is true, if the target language
74
     * is the same as the [[sourceLanguage|source language]], the message
75
     * will NOT be translated.
76
     *
77
     * If a translation is not found, a [[EVENT_MISSING_TRANSLATION|missingTranslation]] event will be triggered.
78
     *
79
     * @param string $category the message category
80
     * @param string $message the message to be translated
81
     * @param string $language the target language
82
     * @return string|bool the translated message or false if translation wasn't found or isn't required
83
     */
84
    public function translate($category, $message, $language)
85
    {
86
        if ($this->forceTranslation || $language !== $this->sourceLanguage) {
87
            return $this->translateMessage($category, $message, $language);
88
        }
89

90
        return false;
91
    }
92

93
    /**
94
     * Translates the specified message.
95
     * If the message is not found, a [[EVENT_MISSING_TRANSLATION|missingTranslation]] event will be triggered.
96
     * If there is an event handler, it may provide a [[MissingTranslationEvent::$translatedMessage|fallback translation]].
97
     * If no fallback translation is provided this method will return `false`.
98
     * @param string $category the category that the message belongs to.
99
     * @param string $message the message to be translated.
100
     * @param string $language the target language.
101
     * @return string|bool the translated message or false if translation wasn't found.
102
     */
103
    protected function translateMessage($category, $message, $language)
104
    {
105
        $key = $language . '/' . $category;
106
        if (!isset($this->_messages[$key])) {
107
            $this->_messages[$key] = $this->loadMessages($category, $language);
108
        }
109
        if (isset($this->_messages[$key][$message]) && $this->_messages[$key][$message] !== '') {
110
            return $this->_messages[$key][$message];
111
        } elseif ($this->hasEventHandlers(self::EVENT_MISSING_TRANSLATION)) {
112
            $event = new MissingTranslationEvent([
113
                'category' => $category,
114
                'message' => $message,
115
                'language' => $language,
116
            ]);
117
            $this->trigger(self::EVENT_MISSING_TRANSLATION, $event);
118
            if ($event->translatedMessage !== null) {
119
                return $this->_messages[$key][$message] = $event->translatedMessage;
120
            }
121
        }
122

123
        return $this->_messages[$key][$message] = false;
124
    }
125
}
126

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.