Completed
Push — prepare-travis-for-js ( a7ee60...8c0a43 )
by Carsten
17:00 queued 09:50
created

DbMessageSource::loadMessagesFromDb()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3.0146

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 23
ccs 15
cts 17
cp 0.8824
rs 9.0856
cc 3
eloc 15
nc 3
nop 2
crap 3.0146
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
 * If you don't want to use migration and need SQL instead, files for all databases are in migrations directory.
36
 *
37
 * @author resurtm <[email protected]>
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 Cache|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 7
    public function init()
97
    {
98 7
        parent::init();
99 7
        $this->db = Instance::ensure($this->db, Connection::className());
100 7
        if ($this->enableCaching) {
101
            $this->cache = Instance::ensure($this->cache, Cache::className());
102
        }
103 7
    }
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 6
    protected function loadMessages($category, $language)
116
    {
117 6
        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
        } else {
131 6
            return $this->loadMessagesFromDb($category, $language);
132
        }
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 6
    protected function loadMessagesFromDb($category, $language)
143
    {
144 6
        $mainQuery = (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
145 6
            ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
146 6
            ->where([
147 6
                't1.id' => new Expression('[[t2.id]]'),
148 6
                't1.category' => $category,
149 6
                't2.language' => $language,
150 6
            ]);
151
152 6
        $fallbackLanguage = substr($language, 0, 2);
153 6
        $fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
154
155 6
        if ($fallbackLanguage !== $language) {
156 4
            $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackLanguage), true);
157 6
        } elseif ($language === $fallbackSourceLanguage) {
158
            $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackSourceLanguage), true);
159
        }
160
161 6
        $messages = $mainQuery->createCommand($this->db)->queryAll();
162
163 6
        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 4
    protected function createFallbackQuery($category, $language, $fallbackLanguage)
178
    {
179 4
        return (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
180 4
            ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
181 4
            ->where([
182 4
                't1.id' => new Expression('[[t2.id]]'),
183 4
                't1.category' => $category,
184 4
                't2.language' => $fallbackLanguage,
185 4
            ])->andWhere([
186 4
                'NOT IN', 't2.id', (new Query())->select('[[id]]')->from($this->messageTable)->where(['language' => $language])
187 4
            ]);
188
    }
189
}
190