MessageController.php 12.1 KB
Newer Older
Qiang Xue committed
1 2 3 4
<?php
/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.yiiframework.com/
Qiang Xue committed
5
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
6 7 8
 * @license http://www.yiiframework.com/license/
 */

9 10
namespace yii\console\controllers;

11
use Yii;
12
use yii\console\Controller;
13 14
use yii\console\Exception;
use yii\helpers\FileHelper;
15

Qiang Xue committed
16
/**
17 18
 * Extracts messages to be translated from source files.
 *
Alexander Makarov committed
19 20 21 22 23 24
 * The extracted messages can be saved the following depending on `format`
 * setting in config file:
 *
 * - PHP message source files.
 * - ".po" files.
 * - Database.
Qiang Xue committed
25
 *
26
 * Usage:
27 28
 * 1. Create a configuration file using the 'message/config' command:
 *    yii message/config /path/to/myapp/messages/config.php
29
 * 2. Edit the created config file, adjusting it for your web application needs.
30
 * 3. Run the 'message/extract' command, using created config:
31 32
 *    yii message /path/to/myapp/messages/config.php
 *
Qiang Xue committed
33
 * @author Qiang Xue <qiang.xue@gmail.com>
34
 * @since 2.0
Qiang Xue committed
35
 */
36
class MessageController extends Controller
Qiang Xue committed
37
{
Digimon committed
38 39 40 41
	/**
	 * @var string controller default action ID.
	 */
	public $defaultAction = 'extract';
42 43


Digimon committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
	/**
	 * Creates a configuration file for the "extract" command.
	 *
	 * The generated configuration file contains detailed instructions on
	 * how to customize it to fit for your needs. After customization,
	 * you may use this configuration file with the "extract" command.
	 *
	 * @param string $filePath output file name or alias.
	 * @throws Exception on failure.
	 */
	public function actionConfig($filePath)
	{
		$filePath = Yii::getAlias($filePath);
		if (file_exists($filePath)) {
			if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
				return;
			}
		}
		copy(Yii::getAlias('@yii/views/messageConfig.php'), $filePath);
		echo "Configuration file template created at '{$filePath}'.\n\n";
	}
65

Digimon committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
	/**
	 * Extracts messages to be translated from source code.
	 *
	 * This command will search through source code files and extract
	 * messages that need to be translated in different languages.
	 *
	 * @param string $configFile the path or alias of the configuration file.
	 * You may use the "yii message/config" command to generate
	 * this file and then customize it for your needs.
	 * @throws Exception on failure.
	 */
	public function actionExtract($configFile)
	{
		$configFile = Yii::getAlias($configFile);
		if (!is_file($configFile)) {
			throw new Exception("The configuration file does not exist: $configFile");
		}
83

Digimon committed
84 85 86 87 88 89 90
		$config = array_merge([
			'translator' => 'Yii::t',
			'overwrite' => false,
			'removeUnused' => false,
			'sort' => false,
			'format' => 'php',
		], require($configFile));
Qiang Xue committed
91

Digimon committed
92 93 94 95 96 97 98
		if (!isset($config['sourcePath'], $config['messagePath'], $config['languages'])) {
			throw new Exception('The configuration file must specify "sourcePath", "messagePath" and "languages".');
		}
		if (!is_dir($config['sourcePath'])) {
			throw new Exception("The source path {$config['sourcePath']} is not a valid directory.");
		}
		if (in_array($config['format'], ['php', 'po'])) {
99 100 101
			if (!is_dir($config['messagePath'])) {
				throw new Exception("The message path {$config['messagePath']} is not a valid directory.");
			}
Digimon committed
102 103 104 105 106
		}
		if (empty($config['languages'])) {
			throw new Exception("Languages cannot be empty.");
		}
		if (empty($config['format']) || !in_array($config['format'], ['php', 'po', 'db'])) {
107
			throw new Exception('Format should be either "php", "po" or "db".');
Digimon committed
108
		}
Qiang Xue committed
109

Digimon committed
110
		$files = FileHelper::findFiles(realpath($config['sourcePath']), $config);
Qiang Xue committed
111

Digimon committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
		$messages = [];
		foreach ($files as $file) {
			$messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator']));
		}
		if (in_array($config['format'], ['php', 'po'])) {
			foreach ($config['languages'] as $language) {
				$dir = $config['messagePath'] . DIRECTORY_SEPARATOR . $language;
				if (!is_dir($dir)) {
					@mkdir($dir);
				}
				foreach ($messages as $category => $msgs) {
					$file = str_replace("\\", '/', "$dir/$category." . $config['format']);
					$path = dirname($file);
					if (!is_dir($path)) {
						mkdir($path, 0755, true);
					}
					$msgs = array_values(array_unique($msgs));
					$this->generateMessageFile($msgs, $file, $config['overwrite'], $config['removeUnused'], $config['sort'], $config['format']);
				}
			}
Alexander Makarov committed
132
		} elseif ($config['format'] === 'db') {
Qiang Xue committed
133 134 135
			$db = \Yii::$app->getComponent(isset($config['db']) ? $config['db'] : 'db');
			if (!$db instanceof \yii\db\Connection) {
				throw new Exception('The "db" option must refer to a valid database application component.');
Digimon committed
136
			}
Qiang Xue committed
137
			$sourceMessageTable = isset($config['sourceMessageTable']) ? $config['sourceMessageTable'] : '{{%source_message}}';
138
			$messageTable = isset($config['messageTable']) ? $config['messageTable'] : '{{%message}}';
139
			$this->saveMessagesToDb(
Qiang Xue committed
140 141
				$messages,
				$db,
142
				$sourceMessageTable,
143
				$messageTable,
144
				$config['removeUnused'],
145
				$config['languages']
146
			);
Digimon committed
147 148
		}
	}
Qiang Xue committed
149

Digimon committed
150
	/**
Alexander Makarov committed
151 152 153
	 * Saves messages to database
	 *
	 * @param array $messages
Qiang Xue committed
154
	 * @param \yii\db\Connection $db
Alexander Makarov committed
155
	 * @param string $sourceMessageTable
156
	 * @param string $messageTable
Alexander Makarov committed
157
	 * @param boolean $removeUnused
158
	 * @param array $languages
Alexander Makarov committed
159
	 */
160
	protected function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages)
161
	{
Digimon committed
162 163
		$q = new \yii\db\Query;
		$current = [];
Qiang Xue committed
164

Digimon committed
165 166 167
		foreach ($q->select(['id', 'category', 'message'])->from($sourceMessageTable)->all() as $row) {
			$current[$row['category']][$row['id']] = $row['message'];
		}
Qiang Xue committed
168

Digimon committed
169
		$new = [];
Alexander Makarov committed
170
		$obsolete = [];
171

Digimon committed
172 173
		foreach ($messages as $category => $msgs) {
			$msgs = array_unique($msgs);
174

Digimon committed
175 176
			if (isset($current[$category])) {
				$new[$category] = array_diff($msgs, $current[$category]);
Alexander Makarov committed
177
				$obsolete = array_diff($current[$category], $msgs);
Digimon committed
178 179 180 181
			} else {
				$new[$category] = $msgs;
			}
		}
182

Digimon committed
183
		foreach (array_diff(array_keys($current), array_keys($messages)) as $category) {
Alexander Makarov committed
184
			$obsolete += $current[$category];
Digimon committed
185
		}
186

Digimon committed
187
		if (!$removeUnused) {
Alexander Makarov committed
188
			foreach ($obsolete as $pk => $m) {
189
				if (mb_substr($m, 0, 2) === '@@' && mb_substr($m, -2) === '@@') {
Alexander Makarov committed
190
					unset($obsolete[$pk]);
Digimon committed
191 192 193
				}
			}
		}
194

Alexander Makarov committed
195
		$obsolete = array_keys($obsolete);
Digimon committed
196 197
		echo "Inserting new messages...";
		$savedFlag = false;
198

199
		foreach ($new as $category => $msgs) {
Digimon committed
200 201
			foreach ($msgs as $m) {
				$savedFlag = true;
202

Qiang Xue committed
203
				$db->createCommand()
204 205
				->insert($sourceMessageTable, ['category' => $category, 'message' => $m])->execute();
				$lastId = $db->getLastInsertID();
206 207
				foreach ($languages as $language) {
					$db->createCommand()
208
					->insert($messageTable, ['id' => $lastId, 'language' => $language])->execute();
209
				}
Digimon committed
210 211
			}
		}
212

Digimon committed
213 214
		echo $savedFlag ? "saved.\n" : "nothing new...skipped.\n";
		echo $removeUnused ? "Deleting obsoleted messages..." : "Updating obsoleted messages...";
215

Alexander Makarov committed
216
		if (empty($obsolete)) {
Digimon committed
217 218 219
			echo "nothing obsoleted...skipped.\n";
		} else {
			if ($removeUnused) {
Qiang Xue committed
220
				$db->createCommand()
221 222
				->delete($sourceMessageTable, ['in', 'id', $obsolete])->execute();
				echo "deleted.\n";
Digimon committed
223
			} else {
224
				$last_id = $db->getLastInsertID();
Qiang Xue committed
225
				$db->createCommand()
226
				->update(
Digimon committed
227 228
						$sourceMessageTable,
						['message' => new \yii\db\Expression("CONCAT('@@',message,'@@')")],
Alexander Makarov committed
229
						['in', 'id', $obsolete]
Digimon committed
230
					)->execute();
231 232 233
				foreach ($languages as $language) {
					$db->createCommand()
					->insert($messageTable, ['id' => $last_id, 'language' => $language])->execute();
234
				}
Digimon committed
235 236 237 238
				echo "updated.\n";
			}
		}
	}
239 240


Digimon committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
	/**
	 * Extracts messages from a file
	 *
	 * @param string $fileName name of the file to extract messages from
	 * @param string $translator name of the function used to translate messages
	 * @return array
	 */
	protected function extractMessages($fileName, $translator)
	{
		echo "Extracting messages from $fileName...\n";
		$subject = file_get_contents($fileName);
		$messages = [];
		if (!is_array($translator)) {
			$translator = [$translator];
		}
		foreach ($translator as $currentTranslator) {
			$n = preg_match_all(
				'/\b' . $currentTranslator . '\s*\(\s*(\'.*?(?<!\\\\)\'|".*?(?<!\\\\)")\s*,\s*(\'.*?(?<!\\\\)\'|".*?(?<!\\\\)")\s*[,\)]/s',
				$subject, $matches, PREG_SET_ORDER);
			for ($i = 0; $i < $n; ++$i) {
				if (($pos = strpos($matches[$i][1], '.')) !== false) {
					$category = substr($matches[$i][1], $pos + 1, -1);
				} else {
					$category = substr($matches[$i][1], 1, -1);
				}
				$message = $matches[$i][2];
				$messages[$category][] = eval("return $message;"); // use eval to eliminate quote escape
			}
		}
		return $messages;
	}

	/**
	 * Writes messages into file
	 *
	 * @param array $messages
	 * @param string $fileName name of the file to write to
	 * @param boolean $overwrite if existing file should be overwritten without backup
	 * @param boolean $removeUnused if obsolete translations should be removed
	 * @param boolean $sort if translations should be sorted
	 * @param string $format output format
	 */
	protected function generateMessageFile($messages, $fileName, $overwrite, $removeUnused, $sort, $format)
	{
		echo "Saving messages to $fileName...";
		if (is_file($fileName)) {
287
			if ($format === 'po') {
Digimon committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
				$translated = file_get_contents($fileName);
				preg_match_all('/(?<=msgid ").*(?="\n(#*)msgstr)/', $translated, $keys);
				preg_match_all('/(?<=msgstr ").*(?="\n\n)/', $translated, $values);
				$translated = array_combine($keys[0], $values[0]);
			} else {
				$translated = require($fileName);
			}
			sort($messages);
			ksort($translated);
			if (array_keys($translated) == $messages) {
				echo "nothing new...skipped.\n";
				return;
			}
			$merged = [];
			$untranslated = [];
			foreach ($messages as $message) {
304
				if ($format === 'po') {
Digimon committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
					$message = preg_replace('/\"/', '\"', $message);
				}
				if (array_key_exists($message, $translated) && strlen($translated[$message]) > 0) {
					$merged[$message] = $translated[$message];
				} else {
					$untranslated[] = $message;
				}
			}
			ksort($merged);
			sort($untranslated);
			$todo = [];
			foreach ($untranslated as $message) {
				$todo[$message] = '';
			}
			ksort($translated);
			foreach ($translated as $message => $translation) {
				if (!isset($merged[$message]) && !isset($todo[$message]) && !$removeUnused) {
					if (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@') {
						$todo[$message] = $translation;
					} else {
						$todo[$message] = '@@' . $translation . '@@';
					}
				}
			}
			$merged = array_merge($todo, $merged);
			if ($sort) {
				ksort($merged);
			}
			if (false === $overwrite) {
				$fileName .= '.merged';
			}
336
			if ($format === 'po') {
Qiang Xue committed
337
				$output = '';
338
				foreach ($merged as $k => $v) {
Digimon committed
339 340 341
					$k = preg_replace('/(\")|(\\\")/', "\\\"", $k);
					$v = preg_replace('/(\")|(\\\")/', "\\\"", $v);
					if (substr($v, 0, 2) === '@@' && substr($v, -2) === '@@') {
Qiang Xue committed
342 343
						$output .= "#msgid \"$k\"\n";
						$output .= "#msgstr \"$v\"\n";
Digimon committed
344
					} else {
Qiang Xue committed
345 346
						$output .= "msgid \"$k\"\n";
						$output .= "msgstr \"$v\"\n";
Digimon committed
347
					}
Qiang Xue committed
348
					$output .= "\n";
Digimon committed
349
				}
Qiang Xue committed
350
				$merged = $output;
Digimon committed
351 352 353 354 355 356
			}
			echo "translation merged.\n";
		} else {
			if ($format === 'po') {
				$merged = '';
				sort($messages);
357
				foreach ($messages as $message) {
Digimon committed
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
					$message = preg_replace('/(\")|(\\\")/', '\\\"', $message);
					$merged .= "msgid \"$message\"\n";
					$merged .= "msgstr \"\"\n";
					$merged .= "\n";
				}
			} else {
				$merged = [];
				foreach ($messages as $message) {
					$merged[$message] = '';
				}
				ksort($merged);
			}
			echo "saved.\n";
		}
		if ($format === 'po') {
			$content = $merged;
		} else {
			$array = str_replace("\r", '', var_export($merged, true));
			$content = <<<EOD
Qiang Xue committed
377 378 379 380
<?php
/**
 * Message translations.
 *
381
 * This file is automatically generated by 'yii {$this->id}' command.
Qiang Xue committed
382 383 384 385 386 387 388 389 390 391 392
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
393
 * NOTE: this file must be saved in UTF-8 encoding.
Qiang Xue committed
394 395 396 397
 */
return $array;

EOD;
Digimon committed
398 399 400
		}
		file_put_contents($fileName, $content);
	}
Qiang Xue committed
401
}