Issues (902)

framework/i18n/DbMessageSource.php (2 issues)

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\base\InvalidConfigException;
11
use yii\caching\CacheInterface;
12
use yii\db\Connection;
13
use yii\db\Expression;
14
use yii\db\Query;
15
use yii\di\Instance;
16
use yii\helpers\ArrayHelper;
17
18
/**
19
 * DbMessageSource extends [[MessageSource]] and represents a message source that stores translated
20
 * messages in database.
21
 *
22
 * The database must contain the following two tables: source_message and message.
23
 *
24
 * The `source_message` table stores the messages to be translated, and the `message` table stores
25
 * the translated messages. The name of these two tables can be customized by setting [[sourceMessageTable]]
26
 * and [[messageTable]], respectively.
27
 *
28
 * The database connection is specified by [[db]]. Database schema could be initialized by applying migration:
29
 *
30
 * ```
31
 * yii migrate --migrationPath=@yii/i18n/migrations/
32
 * ```
33
 *
34
 * If you don't want to use migration and need SQL instead, files for all databases are in migrations directory.
35
 *
36
 * @author resurtm <[email protected]>
37
 * @since 2.0
38
 */
39
class DbMessageSource extends MessageSource
40
{
41
    /**
42
     * Prefix which would be used when generating cache key.
43
     * @deprecated This constant has never been used and will be removed in 2.1.0.
44
     */
45
    const CACHE_KEY_PREFIX = 'DbMessageSource';
46
47
    /**
48
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
49
     *
50
     * After the DbMessageSource object is created, if you want to change this property, you should only assign
51
     * it with a DB connection object.
52
     *
53
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
54
     */
55
    public $db = 'db';
56
    /**
57
     * @var CacheInterface|array|string the cache object or the application component ID of the cache object.
58
     * The messages data will be cached using this cache object.
59
     * Note, that to enable caching you have to set [[enableCaching]] to `true`, otherwise setting this property has no effect.
60
     *
61
     * After the DbMessageSource object is created, if you want to change this property, you should only assign
62
     * it with a cache object.
63
     *
64
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
65
     * @see cachingDuration
66
     * @see enableCaching
67
     */
68
    public $cache = 'cache';
69
    /**
70
     * @var string the name of the source message table.
71
     */
72
    public $sourceMessageTable = '{{%source_message}}';
73
    /**
74
     * @var string the name of the translated message table.
75
     */
76
    public $messageTable = '{{%message}}';
77
    /**
78
     * @var int the time in seconds that the messages can remain valid in cache.
79
     * Use 0 to indicate that the cached data will never expire.
80
     * @see enableCaching
81
     */
82
    public $cachingDuration = 0;
83
    /**
84
     * @var bool whether to enable caching translated messages
85
     */
86
    public $enableCaching = false;
87
88
89
    /**
90
     * Initializes the DbMessageSource component.
91
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
92
     * Configured [[cache]] component would also be initialized.
93
     * @throws InvalidConfigException if [[db]] is invalid or [[cache]] is invalid.
94
     */
95 7
    public function init()
96
    {
97 7
        parent::init();
98 7
        $this->db = Instance::ensure($this->db, Connection::className());
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

98
        $this->db = Instance::ensure($this->db, /** @scrutinizer ignore-deprecated */ Connection::className());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
99 7
        if ($this->enableCaching) {
100
            $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
101
        }
102
    }
103
104
    /**
105
     * Loads the message translation for the specified language and category.
106
     * If translation for specific locale code such as `en-US` isn't found it
107
     * tries more generic `en`.
108
     *
109
     * @param string $category the message category
110
     * @param string $language the target language
111
     * @return array the loaded messages. The keys are original messages, and the values
112
     * are translated messages.
113
     */
114 6
    protected function loadMessages($category, $language)
115
    {
116 6
        if ($this->enableCaching) {
117
            $key = [
118
                __CLASS__,
119
                $category,
120
                $language,
121
            ];
122
            $messages = $this->cache->get($key);
123
            if ($messages === false) {
124
                $messages = $this->loadMessagesFromDb($category, $language);
125
                $this->cache->set($key, $messages, $this->cachingDuration);
126
            }
127
128
            return $messages;
129
        }
130
131 6
        return $this->loadMessagesFromDb($category, $language);
132
    }
133
134
    /**
135
     * Loads the messages from database.
136
     * You may override this method to customize the message storage in the database.
137
     * @param string $category the message category.
138
     * @param string $language the target language.
139
     * @return array the messages loaded from database.
140
     */
141 6
    protected function loadMessagesFromDb($category, $language)
142
    {
143 6
        $mainQuery = (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
144 6
            ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
145 6
            ->where([
146 6
                't1.id' => new Expression('[[t2.id]]'),
147 6
                't1.category' => $category,
148 6
                't2.language' => $language,
149 6
            ]);
150
151 6
        $fallbackLanguage = substr($language, 0, 2);
152 6
        $fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
0 ignored issues
show
It seems like $this->sourceLanguage can also be of type null; however, parameter $string of substr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

152
        $fallbackSourceLanguage = substr(/** @scrutinizer ignore-type */ $this->sourceLanguage, 0, 2);
Loading history...
153
154 6
        if ($fallbackLanguage !== $language) {
155 4
            $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackLanguage), true);
156 2
        } elseif ($language === $fallbackSourceLanguage) {
157
            $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackSourceLanguage), true);
158
        }
159
160 6
        $messages = $mainQuery->createCommand($this->db)->queryAll();
161
162 6
        return ArrayHelper::map($messages, 'message', 'translation');
163
    }
164
165
    /**
166
     * The method builds the [[Query]] object for the fallback language messages search.
167
     * Normally is called from [[loadMessagesFromDb]].
168
     *
169
     * @param string $category the message category
170
     * @param string $language the originally requested language
171
     * @param string $fallbackLanguage the target fallback language
172
     * @return Query
173
     * @see loadMessagesFromDb
174
     * @since 2.0.7
175
     */
176 4
    protected function createFallbackQuery($category, $language, $fallbackLanguage)
177
    {
178 4
        return (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
179 4
            ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
180 4
            ->where([
181 4
                't1.id' => new Expression('[[t2.id]]'),
182 4
                't1.category' => $category,
183 4
                't2.language' => $fallbackLanguage,
184 4
            ])->andWhere([
185 4
                'NOT IN', 't2.id', (new Query())->select('[[id]]')->from($this->messageTable)->where(['language' => $language]),
186 4
            ]);
187
    }
188
}
189