Commit 48b8089d by Digimon

code format fixed

parent c3976b0f
...@@ -31,343 +31,324 @@ use yii\helpers\FileHelper; ...@@ -31,343 +31,324 @@ use yii\helpers\FileHelper;
*/ */
class MessageController extends Controller class MessageController extends Controller
{ {
/** /**
* @var string controller default action ID. * @var string controller default action ID.
*/ */
public $defaultAction = 'extract'; public $defaultAction = 'extract';
/** /**
* Creates a configuration file for the "extract" command. * Creates a configuration file for the "extract" command.
* *
* The generated configuration file contains detailed instructions on * The generated configuration file contains detailed instructions on
* how to customize it to fit for your needs. After customization, * how to customize it to fit for your needs. After customization,
* you may use this configuration file with the "extract" command. * you may use this configuration file with the "extract" command.
* *
* @param string $filePath output file name or alias. * @param string $filePath output file name or alias.
* @throws Exception on failure. * @throws Exception on failure.
*/ */
public function actionConfig($filePath) public function actionConfig($filePath)
{ {
$filePath = Yii::getAlias($filePath); $filePath = Yii::getAlias($filePath);
if (file_exists($filePath)) { if (file_exists($filePath)) {
if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) { if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
return; return;
} }
} }
copy(Yii::getAlias('@yii/views/messageConfig.php'), $filePath); copy(Yii::getAlias('@yii/views/messageConfig.php'), $filePath);
echo "Configuration file template created at '{$filePath}'.\n\n"; echo "Configuration file template created at '{$filePath}'.\n\n";
} }
/** /**
* Extracts messages to be translated from source code. * Extracts messages to be translated from source code.
* *
* This command will search through source code files and extract * This command will search through source code files and extract
* messages that need to be translated in different languages. * messages that need to be translated in different languages.
* *
* @param string $configFile the path or alias of the configuration file. * @param string $configFile the path or alias of the configuration file.
* You may use the "yii message/config" command to generate * You may use the "yii message/config" command to generate
* this file and then customize it for your needs. * this file and then customize it for your needs.
* @throws Exception on failure. * @throws Exception on failure.
*/ */
public function actionExtract($configFile) public function actionExtract($configFile)
{ {
$configFile = Yii::getAlias($configFile); $configFile = Yii::getAlias($configFile);
if (!is_file($configFile)) { if (!is_file($configFile)) {
throw new Exception("The configuration file does not exist: $configFile"); throw new Exception("The configuration file does not exist: $configFile");
} }
$config = array_merge( $config = array_merge([
[ 'translator' => 'Yii::t',
'translator' => 'Yii::t', 'overwrite' => false,
'overwrite' => false, 'removeUnused' => false,
'removeUnused' => false, 'sort' => false,
'sort' => false, 'format' => 'php',
'format' => 'php', ], require($configFile));
],
require($configFile)
);
if (!isset($config['sourcePath'], $config['messagePath'], $config['languages'])) { if (!isset($config['sourcePath'], $config['messagePath'], $config['languages'])) {
throw new Exception('The configuration file must specify "sourcePath", "messagePath" and "languages".'); throw new Exception('The configuration file must specify "sourcePath", "messagePath" and "languages".');
} }
if (!is_dir($config['sourcePath'])) { if (!is_dir($config['sourcePath'])) {
throw new Exception("The source path {$config['sourcePath']} is not a valid directory."); throw new Exception("The source path {$config['sourcePath']} is not a valid directory.");
} }
if (in_array($config['format'], ['php', 'po'])) { if (in_array($config['format'], ['php', 'po'])) {
if (!is_dir($config['messagePath'])) { if (!is_dir($config['messagePath'])) {
throw new Exception("The message path {$config['messagePath']} is not a valid directory."); throw new Exception("The message path {$config['messagePath']} is not a valid directory.");
} }
} }
if (empty($config['languages'])) { if (empty($config['languages'])) {
throw new Exception("Languages cannot be empty."); throw new Exception("Languages cannot be empty.");
} }
if (empty($config['format']) || !in_array($config['format'], ['php', 'po', 'db'])) { if (empty($config['format']) || !in_array($config['format'], ['php', 'po', 'db'])) {
throw new Exception('Format should be either "php", "po" or "db".'); throw new Exception('Format should be either "php", "po" or "db".');
} }
$files = FileHelper::findFiles(realpath($config['sourcePath']), $config); $files = FileHelper::findFiles(realpath($config['sourcePath']), $config);
$messages = []; $messages = [];
foreach ($files as $file) { foreach ($files as $file) {
$messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator'])); $messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator']));
} }
if (in_array($config['format'], ['php', 'po'])) { if (in_array($config['format'], ['php', 'po'])) {
foreach ($config['languages'] as $language) { foreach ($config['languages'] as $language) {
$dir = $config['messagePath'] . DIRECTORY_SEPARATOR . $language; $dir = $config['messagePath'] . DIRECTORY_SEPARATOR . $language;
if (!is_dir($dir)) { if (!is_dir($dir)) {
@mkdir($dir); @mkdir($dir);
} }
foreach ($messages as $category => $msgs) { foreach ($messages as $category => $msgs) {
$file = str_replace("\\", '/', "$dir/$category." . $config['format']); $file = str_replace("\\", '/', "$dir/$category." . $config['format']);
$path = dirname($file); $path = dirname($file);
if (!is_dir($path)) { if (!is_dir($path)) {
mkdir($path, 0755, true); mkdir($path, 0755, true);
} }
$msgs = array_values(array_unique($msgs)); $msgs = array_values(array_unique($msgs));
$this->generateMessageFile( $this->generateMessageFile($msgs, $file, $config['overwrite'], $config['removeUnused'], $config['sort'], $config['format']);
$msgs, }
$file, }
$config['overwrite'], }
$config['removeUnused'], if ($config['format'] === 'db') {
$config['sort'], foreach ($config['languages'] as $language) {
$config['format'] foreach ($messages as $category => $msgs) {
); $messages[$category] = array_values(array_unique($msgs));
} $this->saveMessagesToDb($messages, $dbConnection, $sourceMessageTable, $config['removeUnused']);
} }
} }
if ($config['format'] === 'db') { }
$dbConnection = \Yii::$app->getComponent(isset($config['connectionID']) ? $config['connectionID'] : 'db'); }
if (!$dbConnection instanceof \yii\db\Connection) {
$this->usageError('The "connectionID" must refer to a valid database application component.');
}
$sourceMessageTable = !isset($config['sourceMessageTable']) ? 'SourceMessage' : $config['sourceMessageTable'];
foreach ($config['languages'] as $language) {
foreach ($messages as $category => $msgs) {
$messages[$category] = array_values(array_unique($msgs));
$this->saveMessagesToDb($messages, $dbConnection, $sourceMessageTable, $config['removeUnused']);
}
}
}
}
/** /**
* @param $messages * @param $messages
* @param \yii\db\Connection $dbConnection * @param \yii\db\Connection $dbConnection
* @param $sourceMessageTable * @param $sourceMessageTable
* @param $removeUnused * @param $removeUnused
*/ */
protected function saveMessagesToDb($messages, $dbConnection, $sourceMessageTable, $removeUnused) protected function saveMessagesToDb($messages, $dbConnection, $sourceMessageTable, $removeUnused)
{ {
$q = new \yii\db\Query; $q = new \yii\db\Query;
$current = []; $current = [];
foreach ($q->select(['id', 'category', 'message']) foreach ($q->select(['id', 'category', 'message'])->from($sourceMessageTable)->all() as $row) {
->from($sourceMessageTable) $current[$row['category']][$row['id']] = $row['message'];
->all() as $row) { }
$current[$row['category']][$row['id']] = $row['message'];
}
$new = []; $new = [];
$obsoleted = []; $obsoleted = [];
foreach ($messages as $category => $msgs) { foreach ($messages as $category => $msgs) {
$msgs = array_unique($msgs); $msgs = array_unique($msgs);
if (isset($current[$category])) { if (isset($current[$category])) {
$new[$category] = array_diff($msgs, $current[$category]); $new[$category] = array_diff($msgs, $current[$category]);
$obsoleted = array_diff($current[$category], $msgs); $obsoleted = array_diff($current[$category], $msgs);
} else { } else {
$new[$category] = $msgs; $new[$category] = $msgs;
} }
} }
foreach (array_diff(array_keys($current), array_keys($messages)) as $category) { foreach (array_diff(array_keys($current), array_keys($messages)) as $category) {
$obsoleted += $current[$category]; $obsoleted += $current[$category];
} }
if (!$removeUnused) { if (!$removeUnused) {
foreach ($obsoleted as $pk => $m) { foreach ($obsoleted as $pk => $m) {
if (substr($m, 0, 2) === '@@' && substr($m, -2) === '@@') { if (substr($m, 0, 2) === '@@' && substr($m, -2) === '@@') {
unset($obsoleted[$pk]); unset($obsoleted[$pk]);
} }
} }
} }
$obsoleted = array_keys($obsoleted); $obsoleted = array_keys($obsoleted);
echo "Inserting new messages..."; echo "Inserting new messages...";
$savedFlag = false; $savedFlag = false;
foreach ($new as $category => $msgs) { foreach ($new as $category => $msgs) {
foreach ($msgs as $m) { foreach ($msgs as $m) {
$savedFlag = true; $savedFlag = true;
$dbConnection->createCommand() $dbConnection->createCommand()
->insert($sourceMessageTable, ['category' => $category, 'message' => $m])->execute(); ->insert($sourceMessageTable, ['category' => $category, 'message' => $m])->execute();
} }
} }
echo $savedFlag ? "saved.\n" : "nothing new...skipped.\n"; echo $savedFlag ? "saved.\n" : "nothing new...skipped.\n";
echo $removeUnused ? "Deleting obsoleted messages..." : "Updating obsoleted messages..."; echo $removeUnused ? "Deleting obsoleted messages..." : "Updating obsoleted messages...";
if (empty($obsoleted)) { if (empty($obsoleted)) {
echo "nothing obsoleted...skipped.\n"; echo "nothing obsoleted...skipped.\n";
} else { } else {
if ($removeUnused) { if ($removeUnused) {
$dbConnection->createCommand() $dbConnection->createCommand()
->delete($sourceMessageTable, ['in', 'id', $obsoleted])->execute(); ->delete($sourceMessageTable, ['in', 'id', $obsoleted])->execute();
echo "deleted.\n"; echo "deleted.\n";
} else { } else {
$dbConnection->createCommand() $dbConnection->createCommand()
->update( ->update(
$sourceMessageTable, $sourceMessageTable,
['message' => new \yii\db\Expression("CONCAT('@@',message,'@@')")], ['message' => new \yii\db\Expression("CONCAT('@@',message,'@@')")],
['in', 'id', $obsoleted] ['in', 'id', $obsoleted]
)->execute(); )->execute();
echo "updated.\n"; echo "updated.\n";
} }
} }
} }
/**
* 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 * Extracts messages from a file
* *
* @param array $messages * @param string $fileName name of the file to extract messages from
* @param string $fileName name of the file to write to * @param string $translator name of the function used to translate messages
* @param boolean $overwrite if existing file should be overwritten without backup * @return array
* @param boolean $removeUnused if obsolete translations should be removed */
* @param boolean $sort if translations should be sorted protected function extractMessages($fileName, $translator)
* @param string $format output format {
*/ echo "Extracting messages from $fileName...\n";
protected function generateMessageFile($messages, $fileName, $overwrite, $removeUnused, $sort, $format) $subject = file_get_contents($fileName);
{ $messages = [];
echo "Saving messages to $fileName..."; if (!is_array($translator)) {
if (is_file($fileName)) { $translator = [$translator];
if ($format === 'po') { }
$translated = file_get_contents($fileName); foreach ($translator as $currentTranslator) {
preg_match_all('/(?<=msgid ").*(?="\n(#*)msgstr)/', $translated, $keys); $n = preg_match_all(
preg_match_all('/(?<=msgstr ").*(?="\n\n)/', $translated, $values); '/\b' . $currentTranslator . '\s*\(\s*(\'.*?(?<!\\\\)\'|".*?(?<!\\\\)")\s*,\s*(\'.*?(?<!\\\\)\'|".*?(?<!\\\\)")\s*[,\)]/s',
$translated = array_combine($keys[0], $values[0]); $subject, $matches, PREG_SET_ORDER);
} else { for ($i = 0; $i < $n; ++$i) {
$translated = require($fileName); if (($pos = strpos($matches[$i][1], '.')) !== false) {
} $category = substr($matches[$i][1], $pos + 1, -1);
sort($messages); } else {
ksort($translated); $category = substr($matches[$i][1], 1, -1);
if (array_keys($translated) == $messages) { }
echo "nothing new...skipped.\n"; $message = $matches[$i][2];
return; $messages[$category][] = eval("return $message;"); // use eval to eliminate quote escape
} }
$merged = []; }
$untranslated = []; return $messages;
foreach ($messages as $message) { }
if ($format === 'po') {
$message = preg_replace('/\"/', '\"', $message); /**
} * Writes messages into file
if (array_key_exists($message, $translated) && strlen($translated[$message]) > 0) { *
$merged[$message] = $translated[$message]; * @param array $messages
} else { * @param string $fileName name of the file to write to
$untranslated[] = $message; * @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
ksort($merged); * @param string $format output format
sort($untranslated); */
$todo = []; protected function generateMessageFile($messages, $fileName, $overwrite, $removeUnused, $sort, $format)
foreach ($untranslated as $message) { {
$todo[$message] = ''; echo "Saving messages to $fileName...";
} if (is_file($fileName)) {
ksort($translated); if($format === 'po'){
foreach ($translated as $message => $translation) { $translated = file_get_contents($fileName);
if (!isset($merged[$message]) && !isset($todo[$message]) && !$removeUnused) { preg_match_all('/(?<=msgid ").*(?="\n(#*)msgstr)/', $translated, $keys);
if (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@') { preg_match_all('/(?<=msgstr ").*(?="\n\n)/', $translated, $values);
$todo[$message] = $translation; $translated = array_combine($keys[0], $values[0]);
} else { } else {
$todo[$message] = '@@' . $translation . '@@'; $translated = require($fileName);
} }
} sort($messages);
} ksort($translated);
$merged = array_merge($todo, $merged); if (array_keys($translated) == $messages) {
if ($sort) { echo "nothing new...skipped.\n";
ksort($merged); return;
} }
if (false === $overwrite) { $merged = [];
$fileName .= '.merged'; $untranslated = [];
} foreach ($messages as $message) {
if ($format === 'po') { if($format === 'po'){
$out_str = ''; $message = preg_replace('/\"/', '\"', $message);
foreach ($merged as $k => $v) { }
$k = preg_replace('/(\")|(\\\")/', "\\\"", $k); if (array_key_exists($message, $translated) && strlen($translated[$message]) > 0) {
$v = preg_replace('/(\")|(\\\")/', "\\\"", $v); $merged[$message] = $translated[$message];
if (substr($v, 0, 2) === '@@' && substr($v, -2) === '@@') { } else {
$out_str .= "#msgid \"$k\"\n"; $untranslated[] = $message;
$out_str .= "#msgstr \"$v\"\n"; }
} else { }
$out_str .= "msgid \"$k\"\n"; ksort($merged);
$out_str .= "msgstr \"$v\"\n"; sort($untranslated);
} $todo = [];
$out_str .= "\n"; foreach ($untranslated as $message) {
} $todo[$message] = '';
$merged = $out_str; }
} ksort($translated);
echo "translation merged.\n"; foreach ($translated as $message => $translation) {
} else { if (!isset($merged[$message]) && !isset($todo[$message]) && !$removeUnused) {
if ($format === 'po') { if (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@') {
$merged = ''; $todo[$message] = $translation;
sort($messages); } else {
foreach ($messages as $message) { $todo[$message] = '@@' . $translation . '@@';
$message = preg_replace('/(\")|(\\\")/', '\\\"', $message); }
$merged .= "msgid \"$message\"\n"; }
$merged .= "msgstr \"\"\n"; }
$merged .= "\n"; $merged = array_merge($todo, $merged);
} if ($sort) {
} else { ksort($merged);
$merged = []; }
foreach ($messages as $message) { if (false === $overwrite) {
$merged[$message] = ''; $fileName .= '.merged';
} }
ksort($merged); if ($format === 'po'){
} $out_str = '';
echo "saved.\n"; foreach ($merged as $k => $v){
} $k = preg_replace('/(\")|(\\\")/', "\\\"", $k);
if ($format === 'po') { $v = preg_replace('/(\")|(\\\")/', "\\\"", $v);
$content = $merged; if (substr($v, 0, 2) === '@@' && substr($v, -2) === '@@') {
} else { $out_str .= "#msgid \"$k\"\n";
$array = str_replace("\r", '', var_export($merged, true)); $out_str .= "#msgstr \"$v\"\n";
$content = <<<EOD } else {
$out_str .= "msgid \"$k\"\n";
$out_str .= "msgstr \"$v\"\n";
}
$out_str .= "\n";
}
$merged = $out_str;
}
echo "translation merged.\n";
} else {
if ($format === 'po') {
$merged = '';
sort($messages);
foreach($messages as $message) {
$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
<?php <?php
/** /**
* Message translations. * Message translations.
...@@ -389,8 +370,7 @@ class MessageController extends Controller ...@@ -389,8 +370,7 @@ class MessageController extends Controller
return $array; return $array;
EOD; EOD;
} }
file_put_contents($fileName, $content); file_put_contents($fileName, $content);
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment