|
- <?php
-
-
- namespace yii\i18n;
-
- use Yii;
- use yii\base\InvalidConfigException;
- use yii\db\Expression;
- use yii\di\Instance;
- use yii\helpers\ArrayHelper;
- use yii\caching\Cache;
- use yii\db\Connection;
- use yii\db\Query;
-
-
- class DbMessageSource extends MessageSource
- {
-
-
- const CACHE_KEY_PREFIX = 'DbMessageSource';
-
-
-
- public $db = 'db';
-
-
- public $cache = 'cache';
-
-
- public $sourceMessageTable = '{{%source_message}}';
-
-
- public $messageTable = '{{%message}}';
-
-
- public $cachingDuration = 0;
-
-
- public $enableCaching = false;
-
-
-
-
- public function init()
- {
- parent::init();
- $this->db = Instance::ensure($this->db, Connection::className());
- if ($this->enableCaching) {
- $this->cache = Instance::ensure($this->cache, Cache::className());
- }
- }
-
-
-
- protected function loadMessages($category, $language)
- {
- if ($this->enableCaching) {
- $key = [
- __CLASS__,
- $category,
- $language,
- ];
- $messages = $this->cache->get($key);
- if ($messages === false) {
- $messages = $this->loadMessagesFromDb($category, $language);
- $this->cache->set($key, $messages, $this->cachingDuration);
- }
-
- return $messages;
- } else {
- return $this->loadMessagesFromDb($category, $language);
- }
- }
-
-
-
- protected function loadMessagesFromDb($category, $language)
- {
- $mainQuery = (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
- ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
- ->where([
- 't1.id' => new Expression('[[t2.id]]'),
- 't1.category' => $category,
- 't2.language' => $language,
- ]);
-
- $fallbackLanguage = substr($language, 0, 2);
- $fallbackSourceLanguage = substr($this->sourceLanguage, 0, 2);
-
- if ($fallbackLanguage !== $language) {
- $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackLanguage), true);
- } elseif ($language === $fallbackSourceLanguage) {
- $mainQuery->union($this->createFallbackQuery($category, $language, $fallbackSourceLanguage), true);
- }
-
- $messages = $mainQuery->createCommand($this->db)->queryAll();
-
- return ArrayHelper::map($messages, 'message', 'translation');
- }
-
-
-
- protected function createFallbackQuery($category, $language, $fallbackLanguage)
- {
- return (new Query())->select(['message' => 't1.message', 'translation' => 't2.translation'])
- ->from(['t1' => $this->sourceMessageTable, 't2' => $this->messageTable])
- ->where([
- 't1.id' => new Expression('[[t2.id]]'),
- 't1.category' => $category,
- 't2.language' => $fallbackLanguage,
- ])->andWhere([
- 'NOT IN', 't2.id', (new Query())->select('[[id]]')->from($this->messageTable)->where(['language' => $language])
- ]);
- }
- }
|