PageRenderTime 327ms CodeModel.GetById 59ms RepoModel.GetById 2ms app.codeStats 0ms

/framework/cli/commands/MessageCommand.php

https://github.com/ArnauAregall/yii
PHP | 228 lines | 169 code | 21 blank | 38 comment | 30 complexity | 8cd5f19e9e0221d257951bbb4091c46f MD5 | raw file
Possible License(s): BSD-2-Clause, GPL-2.0, BSD-3-Clause, LGPL-2.1
  1. <?php
  2. /**
  3. * MessageCommand class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * MessageCommand extracts messages to be translated from source files.
  12. * The extracted messages are saved as PHP message source files
  13. * under the specified directory.
  14. *
  15. * @author Qiang Xue <qiang.xue@gmail.com>
  16. * @package system.cli.commands
  17. * @since 1.0
  18. */
  19. class MessageCommand extends CConsoleCommand
  20. {
  21. public function getHelp()
  22. {
  23. return <<<EOD
  24. USAGE
  25. yiic message <config-file>
  26. DESCRIPTION
  27. This command searches for messages to be translated in the specified
  28. source files and compiles them into PHP arrays as message source.
  29. PARAMETERS
  30. * config-file: required, the path of the configuration file. You can find
  31. an example in framework/messages/config.php.
  32. The file can be placed anywhere and must be a valid PHP script which
  33. returns an array of name-value pairs. Each name-value pair represents
  34. a configuration option.
  35. The following options are available:
  36. - sourcePath: string, root directory of all source files.
  37. - messagePath: string, root directory containing message translations.
  38. - languages: array, list of language codes that the extracted messages
  39. should be translated to. For example, array('zh_cn','en_au').
  40. - fileTypes: array, a list of file extensions (e.g. 'php', 'xml').
  41. Only the files whose extension name can be found in this list
  42. will be processed. If empty, all files will be processed.
  43. - exclude: array, a list of directory and file exclusions. Each
  44. exclusion can be either a name or a path. If a file or directory name
  45. or path matches the exclusion, it will not be copied. For example,
  46. an exclusion of '.svn' will exclude all files and directories whose
  47. name is '.svn'. And an exclusion of '/a/b' will exclude file or
  48. directory 'sourcePath/a/b'.
  49. - translator: the name of the function for translating messages.
  50. Defaults to 'Yii::t'. This is used as a mark to find messages to be
  51. translated. Accepts both string for single function name or array for
  52. multiple function names.
  53. - overwrite: if message file must be overwritten with the merged messages.
  54. - removeOld: if message no longer needs translation it will be removed,
  55. instead of being enclosed between a pair of '@@' marks.
  56. - sort: sort messages by key when merging, regardless of their translation
  57. state (new, obsolete, translated.)
  58. EOD;
  59. }
  60. /**
  61. * Execute the action.
  62. * @param array $args command line parameters specific for this command
  63. */
  64. public function run($args)
  65. {
  66. if(!isset($args[0]))
  67. $this->usageError('the configuration file is not specified.');
  68. if(!is_file($args[0]))
  69. $this->usageError("the configuration file {$args[0]} does not exist.");
  70. $config=require_once($args[0]);
  71. $translator='Yii::t';
  72. extract($config);
  73. if(!isset($sourcePath,$messagePath,$languages))
  74. $this->usageError('The configuration file must specify "sourcePath", "messagePath" and "languages".');
  75. if(!is_dir($sourcePath))
  76. $this->usageError("The source path $sourcePath is not a valid directory.");
  77. if(!is_dir($messagePath))
  78. $this->usageError("The message path $messagePath is not a valid directory.");
  79. if(empty($languages))
  80. $this->usageError("Languages cannot be empty.");
  81. if(!isset($overwrite))
  82. $overwrite = false;
  83. if(!isset($removeOld))
  84. $removeOld = false;
  85. if(!isset($sort))
  86. $sort = false;
  87. $options=array();
  88. if(isset($fileTypes))
  89. $options['fileTypes']=$fileTypes;
  90. if(isset($exclude))
  91. $options['exclude']=$exclude;
  92. $files=CFileHelper::findFiles(realpath($sourcePath),$options);
  93. $messages=array();
  94. foreach($files as $file)
  95. $messages=array_merge_recursive($messages,$this->extractMessages($file,$translator));
  96. foreach($languages as $language)
  97. {
  98. $dir=$messagePath.DIRECTORY_SEPARATOR.$language;
  99. if(!is_dir($dir))
  100. @mkdir($dir);
  101. foreach($messages as $category=>$msgs)
  102. {
  103. $msgs=array_values(array_unique($msgs));
  104. $this->generateMessageFile($msgs,$dir.DIRECTORY_SEPARATOR.$category.'.php',$overwrite,$removeOld,$sort);
  105. }
  106. }
  107. }
  108. protected function extractMessages($fileName,$translator)
  109. {
  110. echo "Extracting messages from $fileName...\n";
  111. $subject=file_get_contents($fileName);
  112. $messages=array();
  113. if(!is_array($translator))
  114. $translator=array($translator);
  115. foreach ($translator as $currentTranslator)
  116. {
  117. $n=preg_match_all('/\b'.$currentTranslator.'\s*\(\s*(\'[\w.]*?(?<!\.)\'|"[\w.]*?(?<!\.)")\s*,\s*(\'.*?(?<!\\\\)\'|".*?(?<!\\\\)")\s*[,\)]/s',$subject,$matches,PREG_SET_ORDER);
  118. for($i=0;$i<$n;++$i)
  119. {
  120. if(($pos=strpos($matches[$i][1],'.'))!==false)
  121. $category=substr($matches[$i][1],$pos+1,-1);
  122. else
  123. $category=substr($matches[$i][1],1,-1);
  124. $message=$matches[$i][2];
  125. $messages[$category][]=eval("return $message;"); // use eval to eliminate quote escape
  126. }
  127. }
  128. return $messages;
  129. }
  130. protected function generateMessageFile($messages,$fileName,$overwrite,$removeOld,$sort)
  131. {
  132. echo "Saving messages to $fileName...";
  133. if(is_file($fileName))
  134. {
  135. $translated=require($fileName);
  136. sort($messages);
  137. ksort($translated);
  138. if(array_keys($translated)==$messages)
  139. {
  140. echo "nothing new...skipped.\n";
  141. return;
  142. }
  143. $merged=array();
  144. $untranslated=array();
  145. foreach($messages as $message)
  146. {
  147. if(!empty($translated[$message]))
  148. $merged[$message]=$translated[$message];
  149. else
  150. $untranslated[]=$message;
  151. }
  152. ksort($merged);
  153. sort($untranslated);
  154. $todo=array();
  155. foreach($untranslated as $message)
  156. $todo[$message]='';
  157. ksort($translated);
  158. foreach($translated as $message=>$translation)
  159. {
  160. if(!isset($merged[$message]) && !isset($todo[$message]) && !$removeOld)
  161. {
  162. if(substr($translation,0,2)==='@@' && substr($translation,-2)==='@@')
  163. $todo[$message]=$translation;
  164. else
  165. $todo[$message]='@@'.$translation.'@@';
  166. }
  167. }
  168. $merged=array_merge($todo,$merged);
  169. if($sort)
  170. ksort($merged);
  171. if($overwrite === false)
  172. $fileName.='.merged';
  173. echo "translation merged.\n";
  174. }
  175. else
  176. {
  177. $merged=array();
  178. foreach($messages as $message)
  179. $merged[$message]='';
  180. ksort($merged);
  181. echo "saved.\n";
  182. }
  183. $array=str_replace("\r",'',var_export($merged,true));
  184. $content=<<<EOD
  185. <?php
  186. /**
  187. * Message translations.
  188. *
  189. * This file is automatically generated by 'yiic message' command.
  190. * It contains the localizable messages extracted from source code.
  191. * You may modify this file by translating the extracted messages.
  192. *
  193. * Each array element represents the translation (value) of a message (key).
  194. * If the value is empty, the message is considered as not translated.
  195. * Messages that no longer need translation will have their translations
  196. * enclosed between a pair of '@@' marks.
  197. *
  198. * Message string can be used with plural forms format. Check i18n section
  199. * of the guide for details.
  200. *
  201. * NOTE, this file must be saved in UTF-8 encoding.
  202. */
  203. return $array;
  204. EOD;
  205. file_put_contents($fileName, $content);
  206. }
  207. }