Completed
Push — 7964-i18n-fallback ( 32c424 )
by Dmitry
08:04
created

DbMessageSource::loadMessagesFromDb()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3.0175

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 23
ccs 14
cts 16
cp 0.875
rs 9.0856
cc 3
eloc 15
nc 3
nop 2
crap 3.0175
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
use yii\base\InvalidConfigException;
12
use yii\db\Expression;
13
use yii\di\Instance;
14
use yii\helpers\ArrayHelper;
15
use yii\caching\Cache;
16
use yii\db\Connection;
17
use yii\db\Query;
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
 * @author resurtm <[email protected]>
36
 * @since 2.0
37
 */
38
class DbMessageSource extends MessageSource
39
{
40
    /**
41
     * Prefix which would be used when generating cache key.
42
     * @deprecated This constant has never been used and will be removed in 2.1.0.
43
     */
44
    const CACHE_KEY_PREFIX = 'DbMessageSource';
45
46
    /**
47
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
48
     *
49
     * After the DbMessageSource object is created, if you want to change this property, you should only assign
50
     * it with a DB connection object.
51
     *
52
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
53
     */
54
    public $db = 'db';
55
    /**
56
     * @var Cache|array|string the cache object or the application component ID of the cache object.
57
     * The messages data will be cached using this cache object.
58
     * Note, that to enable caching you have to set [[enableCaching]] to `true`, otherwise setting this property has no effect.
59
     *
60
     * After the DbMessageSource object is created, if you want to change this property, you should only assign
61
     * it with a cache object.
62
     *
63
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
64
     * @see cachingDuration
65
     * @see enableCaching
66
     */
67
    public $cache = 'cache';
68
    /**
69
     * @var string the name of the source message table.
70
     */
71
    public $sourceMessageTable = '{{%source_message}}';
72
    /**
73
     * @var string the name of the translated message table.
74
     */
75
    public $messageTable = '{{%message}}';
76
    /**
77
     * @var integer the time in seconds that the messages can remain valid in cache.
78
     * Use 0 to indicate that the cached data will never expire.
79
     * @see enableCaching
80
     */
81
    public $cachingDuration = 0;
82
    /**
83
     * @var boolean whether to enable caching translated messages
84
     */
85
    public $enableCaching = false;
86
87
88
    /**
89
     * Initializes the DbMessageSource component.
90
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
91
     * Configured [[cache]] component would also be initialized.
92
     * @throws InvalidConfigException if [[db]] is invalid or [[cache]] is invalid.
93
     */
94 10
    public function init()
95
    {
96 10
        parent::init();
97 10
        $this->db = Instance::ensure($this->db, Connection::className());
98 10
        if ($this->enableCaching) {
99
            $this->cache = Instance::ensure($this->cache, Cache::className());
100
        }
101 10
    }
102
103
    /**
104
     * Loads the message translation for the specified language and category.
105
     * If translation for specific locale code such as `en-US` isn't found it
106
     * tries more generic `en`.
107
     *
108
     * @param string $category the message category
109
     * @param string $language the target language
110
     * @return array the loaded messages. The keys are original messages, and the values
111
     * are translated messages.
112
     */
113 6
    protected function loadMessages($category, $language)
114
    {
115 6
        if ($this->enableCaching) {
116
            $key = [
117
                __CLASS__,
118
                $category,
119
                $language,
120
            ];
121
            $messages = $this->cache->get($key);
122
            if ($messages === false) {
123
                $messages = $this->loadMessagesFromDb($category, $language);
124
                $this->cache->set($key, $messages, $this->cachingDuration);
125
            }
126
127
            return $messages;
128
        } else {
129 6
            return $this->loadMessagesFromDb($category, $language);
130
        }
131
    }
132
133
    /**
134
     * Loads the messages from database.
135
     * You may override this method to customize the message storage in the database.
136
     * @param string $category the message category.
137
     * @param string $language the target language.
138
     * @return array the messages loaded from database.
139
     */
140 6
    protected function loadMessagesFromDb($category, $language)
141
    {
142 6
        $mainQuery = (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
143 6
            ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
144 6
            ->where([
145 6
                't1.id' => new Expression('[[t2.id]]'),
146 6
                't1.category' => $category,
147
                't2.language' => $language
148 6
            ]);
149
150 6
        $fallbackLanguage = substr($language, 0, 2);
151 6
        $fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
152
153 6
        if ($fallbackLanguage !== $language) {
154 4
            $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackLanguage), true);
155 6
        } elseif ($language === $fallbackSourceLanguage) {
156
            $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackSourceLanguage), true);
157
        }
158
159 6
        $messages = $mainQuery->createCommand($this->db)->queryAll();
160
161 6
        return ArrayHelper::map($messages, 'message', 'translation');
162
    }
163
164
    /**
165
     * The method builds the [[Query]] object for the fallback language messages search.
166
     * Normally is called from [[loadMessagesFromDb]].
167
     *
168
     * @param string $category the message category
169
     * @param string $language the originally requested language
170
     * @param string $fallbackLanguage the target fallback language
171
     * @return Query
172
     * @see loadMessagesFromDb
173
     * @since 2.0.7
174
     */
175 4
    protected function createFallbackQuery($category, $language, $fallbackLanguage)
176
    {
177 4
        return (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
178 4
            ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
179 4
            ->where([
180 4
                't1.id' => new Expression('[[t2.id]]'),
181 4
                't1.category' => $category,
182
                't2.language' => $fallbackLanguage
183 4
            ])->andWhere([
184 4
                'NOT IN', 't2.id', (new Query())->select('[[id]]')->from($this->messageTable)->where(['language' => $language])
185 4
            ]);
186
    }
187
}
188