MessageController.php 7.4 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
 * This command extracts messages to be translated from source files.
Qiang Xue committed
18 19 20
 * The extracted messages are saved as PHP message source files
 * under the specified directory.
 *
21
 * Usage:
22 23
 * 1. Create a configuration file using the 'message/config' command:
 *    yii message/config /path/to/myapp/messages/config.php
24
 * 2. Edit the created config file, adjusting it for your web application needs.
25
 * 3. Run the 'message/extract' extract, using created config:
26 27
 *    yii message /path/to/myapp/messages/config.php
 *
Qiang Xue committed
28
 * @author Qiang Xue <qiang.xue@gmail.com>
29
 * @since 2.0
Qiang Xue committed
30
 */
31
class MessageController extends Controller
Qiang Xue committed
32
{
33 34 35
	/**
	 * @var string controller default action ID.
	 */
36 37 38
	public $defaultAction = 'extract';


Qiang Xue committed
39
	/**
40
	 * Creates a configuration file for the "extract" command.
41
	 *
42 43 44
	 * 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.
45
	 *
46
	 * @param string $filePath output file name or alias.
47 48 49 50
	 * @throws Exception on failure.
	 */
	public function actionConfig($filePath)
	{
51
		$filePath = Yii::getAlias($filePath);
52 53 54 55 56 57 58 59 60 61 62
		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";
	}

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

Alexander Makarov committed
79
		$config = array_merge([
80 81 82 83
			'translator' => 'Yii::t',
			'overwrite' => false,
			'removeUnused' => false,
			'sort' => false,
Alexander Makarov committed
84
		], require($configFile));
Qiang Xue committed
85

86
		if (!isset($config['sourcePath'], $config['messagePath'], $config['languages'])) {
87
			throw new Exception('The configuration file must specify "sourcePath", "messagePath" and "languages".');
resurtm committed
88
		}
89 90
		if (!is_dir($config['sourcePath'])) {
			throw new Exception("The source path {$config['sourcePath']} is not a valid directory.");
resurtm committed
91
		}
92 93
		if (!is_dir($config['messagePath'])) {
			throw new Exception("The message path {$config['messagePath']} is not a valid directory.");
resurtm committed
94
		}
95
		if (empty($config['languages'])) {
96
			throw new Exception("Languages cannot be empty.");
resurtm committed
97
		}
Qiang Xue committed
98

99
		$files = FileHelper::findFiles(realpath($config['sourcePath']), $config);
Qiang Xue committed
100

Alexander Makarov committed
101
		$messages = [];
resurtm committed
102
		foreach ($files as $file) {
Qiang Xue committed
103
			$messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator']));
resurtm committed
104
		}
Qiang Xue committed
105

106 107
		foreach ($config['languages'] as $language) {
			$dir = $config['messagePath'] . DIRECTORY_SEPARATOR . $language;
resurtm committed
108
			if (!is_dir($dir)) {
Qiang Xue committed
109
				@mkdir($dir);
resurtm committed
110 111
			}
			foreach ($messages as $category => $msgs) {
112 113 114 115 116
				$file = str_replace("\\", '/', "$dir/$category.php");
				$path = dirname($file);
				if (!is_dir($path)) {
					mkdir($path, 0755, true);
				}
resurtm committed
117
				$msgs = array_values(array_unique($msgs));
118
				$this->generateMessageFile($msgs, $file, $config['overwrite'], $config['removeUnused'], $config['sort']);
Qiang Xue committed
119 120 121 122
			}
		}
	}

Alexander Makarov committed
123 124 125 126 127 128 129
	/**
	 * 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
	 */
resurtm committed
130
	protected function extractMessages($fileName, $translator)
Qiang Xue committed
131 132
	{
		echo "Extracting messages from $fileName...\n";
resurtm committed
133
		$subject = file_get_contents($fileName);
Alexander Makarov committed
134
		$messages = [];
135
		if (!is_array($translator)) {
Alexander Makarov committed
136
			$translator = [$translator];
137 138 139 140 141 142 143 144 145 146 147 148 149
		}
		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
resurtm committed
150
			}
Qiang Xue committed
151 152 153 154
		}
		return $messages;
	}

Alexander Makarov committed
155 156 157 158 159 160
	/**
	 * 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
161
	 * @param boolean $removeUnused if obsolete translations should be removed
Alexander Makarov committed
162 163
	 * @param boolean $sort if translations should be sorted
	 */
164
	protected function generateMessageFile($messages, $fileName, $overwrite, $removeUnused, $sort)
Qiang Xue committed
165 166
	{
		echo "Saving messages to $fileName...";
resurtm committed
167 168
		if (is_file($fileName)) {
			$translated = require($fileName);
Qiang Xue committed
169 170
			sort($messages);
			ksort($translated);
resurtm committed
171
			if (array_keys($translated) == $messages) {
Qiang Xue committed
172 173 174
				echo "nothing new...skipped.\n";
				return;
			}
Alexander Makarov committed
175 176
			$merged = [];
			$untranslated = [];
resurtm committed
177
			foreach ($messages as $message) {
178
				if (array_key_exists($message, $translated) && strlen($translated[$message]) > 0) {
resurtm committed
179 180 181 182
					$merged[$message] = $translated[$message];
				} else {
					$untranslated[] = $message;
				}
Qiang Xue committed
183 184 185
			}
			ksort($merged);
			sort($untranslated);
Alexander Makarov committed
186
			$todo = [];
resurtm committed
187 188 189
			foreach ($untranslated as $message) {
				$todo[$message] = '';
			}
Qiang Xue committed
190
			ksort($translated);
resurtm committed
191
			foreach ($translated as $message => $translation) {
192
				if (!isset($merged[$message]) && !isset($todo[$message]) && !$removeUnused) {
resurtm committed
193
					if (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@') {
194
						$todo[$message] = $translation;
resurtm committed
195 196 197
					} else {
						$todo[$message] = '@@' . $translation . '@@';
					}
Qiang Xue committed
198 199
				}
			}
resurtm committed
200 201
			$merged = array_merge($todo, $merged);
			if ($sort) {
Qiang Xue committed
202
				ksort($merged);
resurtm committed
203 204 205 206
			}
			if (false === $overwrite) {
				$fileName .= '.merged';
			}
Qiang Xue committed
207
			echo "translation merged.\n";
resurtm committed
208
		} else {
Alexander Makarov committed
209
			$merged = [];
resurtm committed
210 211 212
			foreach ($messages as $message) {
				$merged[$message] = '';
			}
Qiang Xue committed
213 214 215
			ksort($merged);
			echo "saved.\n";
		}
resurtm committed
216 217
		$array = str_replace("\r", '', var_export($merged, true));
		$content = <<<EOD
Qiang Xue committed
218 219 220 221
<?php
/**
 * Message translations.
 *
222
 * This file is automatically generated by 'yii {$this->id}' command.
Qiang Xue committed
223 224 225 226 227 228 229 230 231 232 233
 * 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.
 *
234
 * NOTE: this file must be saved in UTF-8 encoding.
Qiang Xue committed
235 236 237 238 239 240 241
 */
return $array;

EOD;
		file_put_contents($fileName, $content);
	}
}