MessageController.php 7.25 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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
	 * @param string $filePath output file name.
	 * @throws Exception on failure.
	 */
	public function actionConfig($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";
	}

	/**
	 * Extracts messages to be translated from source code.
62
	 *
63 64
	 * This command will search through source code files and extract
	 * messages that need to be translated in different languages.
65
	 *
66 67 68 69
	 * @param string $configFile the path 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.
Qiang Xue committed
70
	 */
71
	public function actionExtract($configFile)
Qiang Xue committed
72
	{
73
		if (!is_file($configFile)) {
Qiang Xue committed
74
			throw new Exception("The configuration file does not exist: $configFile");
resurtm committed
75
		}
76

77 78 79 80 81 82
		$config = array_merge(array(
			'translator' => 'Yii::t',
			'overwrite' => false,
			'removeUnused' => false,
			'sort' => false,
		), require($configFile));
Qiang Xue committed
83

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

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

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

104 105
		foreach ($config['languages'] as $language) {
			$dir = $config['messagePath'] . DIRECTORY_SEPARATOR . $language;
resurtm committed
106
			if (!is_dir($dir)) {
Qiang Xue committed
107
				@mkdir($dir);
resurtm committed
108 109 110
			}
			foreach ($messages as $category => $msgs) {
				$msgs = array_values(array_unique($msgs));
111 112 113 114
				$this->generateMessageFile($msgs, $dir . DIRECTORY_SEPARATOR . $category . '.php',
					$config['overwrite'],
					$config['removeUnused'],
					$config['sort']);
Qiang Xue committed
115 116 117 118
			}
		}
	}

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

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

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