DbMessageSource.php 5.15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\i18n;

use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\caching\Cache;
use yii\db\Connection;
use yii\db\Query;

/**
 * DbMessageSource extends [[MessageSource]] and represents a message source that stores translated
 * messages in database.
 *
 * The database must contain the following two tables:
 *
 * ~~~
 * CREATE TABLE tbl_source_message (
 *     id INTEGER PRIMARY KEY,
 *     category VARCHAR(32),
 *     message TEXT
 * );
 *
 * CREATE TABLE tbl_message (
 *     id INTEGER,
 *     language VARCHAR(16),
 *     translation TEXT,
 *     PRIMARY KEY (id, language),
 *     CONSTRAINT fk_message_source_message FOREIGN KEY (id)
 *         REFERENCES tbl_source_message (id) ON DELETE CASCADE ON UPDATE RESTRICT
 * );
 * ~~~
 *
 * The `tbl_source_message` table stores the messages to be translated, and the `tbl_message` table stores
 * the translated messages. The name of these two tables can be customized by setting [[sourceMessageTable]]
 * and [[messageTable]], respectively.
 *
 * @author resurtm <resurtm@gmail.com>
 * @since 2.0
 */
class DbMessageSource extends MessageSource
{
	/**
	 * Prefix which would be used when generating cache key.
	 */
	const CACHE_KEY_PREFIX = 'DbMessageSource';

	/**
	 * @var Connection|string the DB connection object or the application component ID of the DB connection.
	 * After the DbMessageSource object is created, if you want to change this property, you should only assign
	 * it with a DB connection object.
	 */
	public $db = 'db';
	/**
	 * @var Cache|string the cache object or the application component ID of the cache object.
	 * The messages data will be cached using this cache object. Note, this property has meaning only
	 * in case [[cachingDuration]] set to non-zero value.
	 * After the DbMessageSource object is created, if you want to change this property, you should only assign
	 * it with a cache object.
	 */
	public $cache = 'cache';
	/**
69
	 * @var string the name of the source message table.
70
	 */
71
	public $sourceMessageTable = 'tbl_source_message';
72
	/**
73
	 * @var string the name of the translated message table.
74
	 */
75
	public $messageTable = 'tbl_message';
76 77
	/**
	 * @var integer the time in seconds that the messages can remain valid in cache.
78 79
	 * Use 0 to indicate that the cached data will never expire.
	 * @see enableCaching
80 81
	 */
	public $cachingDuration = 0;
82 83 84 85
	/**
	 * @var boolean whether to enable caching translated messages
	 */
	public $enableCaching = false;
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

	/**
	 * Initializes the DbMessageSource component.
	 * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
	 * Configured [[cache]] component would also be initialized.
	 * @throws InvalidConfigException if [[db]] is invalid or [[cache]] is invalid.
	 */
	public function init()
	{
		parent::init();
		if (is_string($this->db)) {
			$this->db = Yii::$app->getComponent($this->db);
		}
		if (!$this->db instanceof Connection) {
			throw new InvalidConfigException("DbMessageSource::db must be either a DB connection instance or the application component ID of a DB connection.");
		}
102
		if ($this->enableCaching) {
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
			if (is_string($this->cache)) {
				$this->cache = Yii::$app->getComponent($this->cache);
			}
			if (!$this->cache instanceof Cache) {
				throw new InvalidConfigException("DbMessageSource::cache must be either a cache object or the application component ID of the cache object.");
			}
		}
	}

	/**
	 * Loads the message translation for the specified language and category.
	 * Child classes should override this method to return the message translations of
	 * the specified language and category.
	 * @param string $category the message category
	 * @param string $language the target language
	 * @return array the loaded messages. The keys are original messages, and the values
	 * are translated messages.
	 */
	protected function loadMessages($category, $language)
	{
123
		if ($this->enableCaching) {
Alexander Makarov committed
124
			$key = [
125 126 127
				__CLASS__,
				$category,
				$language,
Alexander Makarov committed
128
			];
129 130
			$messages = $this->cache->get($key);
			if ($messages === false) {
131
				$messages = $this->loadMessagesFromDb($category, $language);
132 133 134
				$this->cache->set($key, $messages, $this->cachingDuration);
			}
			return $messages;
135 136
		} else {
			return $this->loadMessagesFromDb($category, $language);
137 138 139 140 141 142 143 144 145 146
		}
	}

	/**
	 * Loads the messages from database.
	 * You may override this method to customize the message storage in the database.
	 * @param string $category the message category.
	 * @param string $language the target language.
	 * @return array the messages loaded from database.
	 */
147
	protected function loadMessagesFromDb($category, $language)
148 149
	{
		$query = new Query();
Alexander Makarov committed
150 151
		$messages = $query->select(['t1.message message', 't2.translation translation'])
			->from([$this->sourceMessageTable . ' t1', $this->messageTable . ' t2'])
152
			->where('t1.id = t2.id AND t1.category = :category AND t2.language = :language')
Alexander Makarov committed
153
			->params([':category' => $category, ':language' => $language])
154 155 156 157 158
			->createCommand($this->db)
			->queryAll();
		return ArrayHelper::map($messages, 'message', 'translation');
	}
}