yii2

Форк
1
/
DbMessageSource.php 
189 строк · 7.0 Кб
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\InvalidConfigException;
12
use yii\caching\CacheInterface;
13
use yii\db\Connection;
14
use yii\db\Expression;
15
use yii\db\Query;
16
use yii\di\Instance;
17
use yii\helpers\ArrayHelper;
18

19
/**
20
 * DbMessageSource extends [[MessageSource]] and represents a message source that stores translated
21
 * messages in database.
22
 *
23
 * The database must contain the following two tables: source_message and message.
24
 *
25
 * The `source_message` table stores the messages to be translated, and the `message` table stores
26
 * the translated messages. The name of these two tables can be customized by setting [[sourceMessageTable]]
27
 * and [[messageTable]], respectively.
28
 *
29
 * The database connection is specified by [[db]]. Database schema could be initialized by applying migration:
30
 *
31
 * ```
32
 * yii migrate --migrationPath=@yii/i18n/migrations/
33
 * ```
34
 *
35
 * If you don't want to use migration and need SQL instead, files for all databases are in migrations directory.
36
 *
37
 * @author resurtm <resurtm@gmail.com>
38
 * @since 2.0
39
 */
40
class DbMessageSource extends MessageSource
41
{
42
    /**
43
     * Prefix which would be used when generating cache key.
44
     * @deprecated This constant has never been used and will be removed in 2.1.0.
45
     */
46
    const CACHE_KEY_PREFIX = 'DbMessageSource';
47

48
    /**
49
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
50
     *
51
     * After the DbMessageSource object is created, if you want to change this property, you should only assign
52
     * it with a DB connection object.
53
     *
54
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
55
     */
56
    public $db = 'db';
57
    /**
58
     * @var CacheInterface|array|string the cache object or the application component ID of the cache object.
59
     * The messages data will be cached using this cache object.
60
     * Note, that to enable caching you have to set [[enableCaching]] to `true`, otherwise setting this property has no effect.
61
     *
62
     * After the DbMessageSource object is created, if you want to change this property, you should only assign
63
     * it with a cache object.
64
     *
65
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
66
     * @see cachingDuration
67
     * @see enableCaching
68
     */
69
    public $cache = 'cache';
70
    /**
71
     * @var string the name of the source message table.
72
     */
73
    public $sourceMessageTable = '{{%source_message}}';
74
    /**
75
     * @var string the name of the translated message table.
76
     */
77
    public $messageTable = '{{%message}}';
78
    /**
79
     * @var int the time in seconds that the messages can remain valid in cache.
80
     * Use 0 to indicate that the cached data will never expire.
81
     * @see enableCaching
82
     */
83
    public $cachingDuration = 0;
84
    /**
85
     * @var bool whether to enable caching translated messages
86
     */
87
    public $enableCaching = false;
88

89

90
    /**
91
     * Initializes the DbMessageSource component.
92
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
93
     * Configured [[cache]] component would also be initialized.
94
     * @throws InvalidConfigException if [[db]] is invalid or [[cache]] is invalid.
95
     */
96
    public function init()
97
    {
98
        parent::init();
99
        $this->db = Instance::ensure($this->db, Connection::className());
100
        if ($this->enableCaching) {
101
            $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
102
        }
103
    }
104

105
    /**
106
     * Loads the message translation for the specified language and category.
107
     * If translation for specific locale code such as `en-US` isn't found it
108
     * tries more generic `en`.
109
     *
110
     * @param string $category the message category
111
     * @param string $language the target language
112
     * @return array the loaded messages. The keys are original messages, and the values
113
     * are translated messages.
114
     */
115
    protected function loadMessages($category, $language)
116
    {
117
        if ($this->enableCaching) {
118
            $key = [
119
                __CLASS__,
120
                $category,
121
                $language,
122
            ];
123
            $messages = $this->cache->get($key);
124
            if ($messages === false) {
125
                $messages = $this->loadMessagesFromDb($category, $language);
126
                $this->cache->set($key, $messages, $this->cachingDuration);
127
            }
128

129
            return $messages;
130
        }
131

132
        return $this->loadMessagesFromDb($category, $language);
133
    }
134

135
    /**
136
     * Loads the messages from database.
137
     * You may override this method to customize the message storage in the database.
138
     * @param string $category the message category.
139
     * @param string $language the target language.
140
     * @return array the messages loaded from database.
141
     */
142
    protected function loadMessagesFromDb($category, $language)
143
    {
144
        $mainQuery = (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
145
            ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
146
            ->where([
147
                't1.id' => new Expression('[[t2.id]]'),
148
                't1.category' => $category,
149
                't2.language' => $language,
150
            ]);
151

152
        $fallbackLanguage = substr($language, 0, 2);
153
        $fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
154

155
        if ($fallbackLanguage !== $language) {
156
            $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackLanguage), true);
157
        } elseif ($language === $fallbackSourceLanguage) {
158
            $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackSourceLanguage), true);
159
        }
160

161
        $messages = $mainQuery->createCommand($this->db)->queryAll();
162

163
        return ArrayHelper::map($messages, 'message', 'translation');
164
    }
165

166
    /**
167
     * The method builds the [[Query]] object for the fallback language messages search.
168
     * Normally is called from [[loadMessagesFromDb]].
169
     *
170
     * @param string $category the message category
171
     * @param string $language the originally requested language
172
     * @param string $fallbackLanguage the target fallback language
173
     * @return Query
174
     * @see loadMessagesFromDb
175
     * @since 2.0.7
176
     */
177
    protected function createFallbackQuery($category, $language, $fallbackLanguage)
178
    {
179
        return (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
180
            ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
181
            ->where([
182
                't1.id' => new Expression('[[t2.id]]'),
183
                't1.category' => $category,
184
                't2.language' => $fallbackLanguage,
185
            ])->andWhere([
186
                'NOT IN', 't2.id', (new Query())->select('[[id]]')->from($this->messageTable)->where(['language' => $language]),
187
            ]);
188
    }
189
}
190

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

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

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

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