MessageController.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\console\controllers;
  8. use Yii;
  9. use yii\console\Exception;
  10. use yii\console\ExitCode;
  11. use yii\db\Connection;
  12. use yii\db\Query;
  13. use yii\di\Instance;
  14. use yii\helpers\Console;
  15. use yii\helpers\FileHelper;
  16. use yii\helpers\VarDumper;
  17. use yii\i18n\GettextPoFile;
  18. /**
  19. * Extracts messages to be translated from source files.
  20. *
  21. * The extracted messages can be saved the following depending on `format`
  22. * setting in config file:
  23. *
  24. * - PHP message source files.
  25. * - ".po" files.
  26. * - Database.
  27. *
  28. * Usage:
  29. * 1. Create a configuration file using the 'message/config' command:
  30. * yii message/config /path/to/myapp/messages/config.php
  31. * 2. Edit the created config file, adjusting it for your web application needs.
  32. * 3. Run the 'message/extract' command, using created config:
  33. * yii message /path/to/myapp/messages/config.php
  34. *
  35. * @author Qiang Xue <qiang.xue@gmail.com>
  36. * @since 2.0
  37. */
  38. class MessageController extends \yii\console\Controller
  39. {
  40. /**
  41. * @var string controller default action ID.
  42. */
  43. public $defaultAction = 'extract';
  44. /**
  45. * @var string required, root directory of all source files.
  46. */
  47. public $sourcePath = '@yii';
  48. /**
  49. * @var string required, root directory containing message translations.
  50. */
  51. public $messagePath = '@yii/messages';
  52. /**
  53. * @var array required, list of language codes that the extracted messages
  54. * should be translated to. For example, ['zh-CN', 'de'].
  55. */
  56. public $languages = [];
  57. /**
  58. * @var string the name of the function for translating messages.
  59. * Defaults to 'Yii::t'. This is used as a mark to find the messages to be
  60. * translated. You may use a string for single function name or an array for
  61. * multiple function names.
  62. */
  63. public $translator = 'Yii::t';
  64. /**
  65. * @var bool whether to sort messages by keys when merging new messages
  66. * with the existing ones. Defaults to false, which means the new (untranslated)
  67. * messages will be separated from the old (translated) ones.
  68. */
  69. public $sort = false;
  70. /**
  71. * @var bool whether the message file should be overwritten with the merged messages
  72. */
  73. public $overwrite = true;
  74. /**
  75. * @var bool whether to remove messages that no longer appear in the source code.
  76. * Defaults to false, which means these messages will NOT be removed.
  77. */
  78. public $removeUnused = false;
  79. /**
  80. * @var bool whether to mark messages that no longer appear in the source code.
  81. * Defaults to true, which means each of these messages will be enclosed with a pair of '@@' marks.
  82. */
  83. public $markUnused = true;
  84. /**
  85. * @var array list of patterns that specify which files/directories should NOT be processed.
  86. * If empty or not set, all files/directories will be processed.
  87. * See helpers/FileHelper::findFiles() description for pattern matching rules.
  88. * If a file/directory matches both a pattern in "only" and "except", it will NOT be processed.
  89. */
  90. public $except = [
  91. '.svn',
  92. '.git',
  93. '.gitignore',
  94. '.gitkeep',
  95. '.hgignore',
  96. '.hgkeep',
  97. '/messages',
  98. '/BaseYii.php', // contains examples about Yii::t()
  99. ];
  100. /**
  101. * @var array list of patterns that specify which files (not directories) should be processed.
  102. * If empty or not set, all files will be processed.
  103. * See helpers/FileHelper::findFiles() description for pattern matching rules.
  104. * If a file/directory matches both a pattern in "only" and "except", it will NOT be processed.
  105. */
  106. public $only = ['*.php'];
  107. /**
  108. * @var string generated file format. Can be "php", "db", "po" or "pot".
  109. */
  110. public $format = 'php';
  111. /**
  112. * @var string connection component ID for "db" format.
  113. */
  114. public $db = 'db';
  115. /**
  116. * @var string custom name for source message table for "db" format.
  117. */
  118. public $sourceMessageTable = '{{%source_message}}';
  119. /**
  120. * @var string custom name for translation message table for "db" format.
  121. */
  122. public $messageTable = '{{%message}}';
  123. /**
  124. * @var string name of the file that will be used for translations for "po" format.
  125. */
  126. public $catalog = 'messages';
  127. /**
  128. * @var array message categories to ignore. For example, 'yii', 'app*', 'widgets/menu', etc.
  129. * @see isCategoryIgnored
  130. */
  131. public $ignoreCategories = [];
  132. /**
  133. * @var string File header in generated PHP file with messages. This property is used only if [[$format]] is "php".
  134. * @since 2.0.13
  135. */
  136. public $phpFileHeader = '';
  137. /**
  138. * @var string|null DocBlock used for messages array in generated PHP file. If `null`, default DocBlock will be used.
  139. * This property is used only if [[$format]] is "php".
  140. * @since 2.0.13
  141. */
  142. public $phpDocBlock;
  143. /**
  144. * @var array Config for messages extraction.
  145. * @see actionExtract()
  146. * @see initConfig()
  147. * @since 2.0.13
  148. */
  149. protected $config;
  150. /**
  151. * {@inheritdoc}
  152. */
  153. public function options($actionID)
  154. {
  155. return array_merge(parent::options($actionID), [
  156. 'sourcePath',
  157. 'messagePath',
  158. 'languages',
  159. 'translator',
  160. 'sort',
  161. 'overwrite',
  162. 'removeUnused',
  163. 'markUnused',
  164. 'except',
  165. 'only',
  166. 'format',
  167. 'db',
  168. 'sourceMessageTable',
  169. 'messageTable',
  170. 'catalog',
  171. 'ignoreCategories',
  172. 'phpFileHeader',
  173. 'phpDocBlock',
  174. ]);
  175. }
  176. /**
  177. * {@inheritdoc}
  178. * @since 2.0.8
  179. */
  180. public function optionAliases()
  181. {
  182. return array_merge(parent::optionAliases(), [
  183. 'c' => 'catalog',
  184. 'e' => 'except',
  185. 'f' => 'format',
  186. 'i' => 'ignoreCategories',
  187. 'l' => 'languages',
  188. 'u' => 'markUnused',
  189. 'p' => 'messagePath',
  190. 'o' => 'only',
  191. 'w' => 'overwrite',
  192. 'S' => 'sort',
  193. 't' => 'translator',
  194. 'm' => 'sourceMessageTable',
  195. 's' => 'sourcePath',
  196. 'r' => 'removeUnused',
  197. ]);
  198. }
  199. /**
  200. * Creates a configuration file for the "extract" command using command line options specified.
  201. *
  202. * The generated configuration file contains parameters required
  203. * for source code messages extraction.
  204. * You may use this configuration file with the "extract" command.
  205. *
  206. * @param string $filePath output file name or alias.
  207. * @return int CLI exit code
  208. * @throws Exception on failure.
  209. */
  210. public function actionConfig($filePath)
  211. {
  212. $filePath = Yii::getAlias($filePath);
  213. $dir = dirname($filePath);
  214. if (file_exists($filePath)) {
  215. if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
  216. return ExitCode::OK;
  217. }
  218. }
  219. $array = VarDumper::export($this->getOptionValues($this->action->id));
  220. $content = <<<EOD
  221. <?php
  222. /**
  223. * Configuration file for 'yii {$this->id}/{$this->defaultAction}' command.
  224. *
  225. * This file is automatically generated by 'yii {$this->id}/{$this->action->id}' command.
  226. * It contains parameters for source code messages extraction.
  227. * You may modify this file to suit your needs.
  228. *
  229. * You can use 'yii {$this->id}/{$this->action->id}-template' command to create
  230. * template configuration file with detailed description for each parameter.
  231. */
  232. return $array;
  233. EOD;
  234. if (FileHelper::createDirectory($dir) === false || file_put_contents($filePath, $content, LOCK_EX) === false) {
  235. $this->stdout("Configuration file was NOT created: '{$filePath}'.\n\n", Console::FG_RED);
  236. return ExitCode::UNSPECIFIED_ERROR;
  237. }
  238. $this->stdout("Configuration file created: '{$filePath}'.\n\n", Console::FG_GREEN);
  239. return ExitCode::OK;
  240. }
  241. /**
  242. * Creates a configuration file template for the "extract" command.
  243. *
  244. * The created configuration file contains detailed instructions on
  245. * how to customize it to fit for your needs. After customization,
  246. * you may use this configuration file with the "extract" command.
  247. *
  248. * @param string $filePath output file name or alias.
  249. * @return int CLI exit code
  250. * @throws Exception on failure.
  251. */
  252. public function actionConfigTemplate($filePath)
  253. {
  254. $filePath = Yii::getAlias($filePath);
  255. if (file_exists($filePath)) {
  256. if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
  257. return ExitCode::OK;
  258. }
  259. }
  260. if (!copy(Yii::getAlias('@yii/views/messageConfig.php'), $filePath)) {
  261. $this->stdout("Configuration file template was NOT created at '{$filePath}'.\n\n", Console::FG_RED);
  262. return ExitCode::UNSPECIFIED_ERROR;
  263. }
  264. $this->stdout("Configuration file template created at '{$filePath}'.\n\n", Console::FG_GREEN);
  265. return ExitCode::OK;
  266. }
  267. /**
  268. * Extracts messages to be translated from source code.
  269. *
  270. * This command will search through source code files and extract
  271. * messages that need to be translated in different languages.
  272. *
  273. * @param string $configFile the path or alias of the configuration file.
  274. * You may use the "yii message/config" command to generate
  275. * this file and then customize it for your needs.
  276. * @throws Exception on failure.
  277. */
  278. public function actionExtract($configFile = null)
  279. {
  280. $this->initConfig($configFile);
  281. $files = FileHelper::findFiles(realpath($this->config['sourcePath']), $this->config);
  282. $messages = [];
  283. foreach ($files as $file) {
  284. $messages = array_merge_recursive($messages, $this->extractMessages($file, $this->config['translator'], $this->config['ignoreCategories']));
  285. }
  286. $catalog = isset($this->config['catalog']) ? $this->config['catalog'] : 'messages';
  287. if (in_array($this->config['format'], ['php', 'po'])) {
  288. foreach ($this->config['languages'] as $language) {
  289. $dir = $this->config['messagePath'] . DIRECTORY_SEPARATOR . $language;
  290. if (!is_dir($dir) && !@mkdir($dir)) {
  291. throw new Exception("Directory '{$dir}' can not be created.");
  292. }
  293. if ($this->config['format'] === 'po') {
  294. $this->saveMessagesToPO($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $catalog, $this->config['markUnused']);
  295. } else {
  296. $this->saveMessagesToPHP($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $this->config['markUnused']);
  297. }
  298. }
  299. } elseif ($this->config['format'] === 'db') {
  300. /** @var Connection $db */
  301. $db = Instance::ensure($this->config['db'], Connection::className());
  302. $sourceMessageTable = isset($this->config['sourceMessageTable']) ? $this->config['sourceMessageTable'] : '{{%source_message}}';
  303. $messageTable = isset($this->config['messageTable']) ? $this->config['messageTable'] : '{{%message}}';
  304. $this->saveMessagesToDb(
  305. $messages,
  306. $db,
  307. $sourceMessageTable,
  308. $messageTable,
  309. $this->config['removeUnused'],
  310. $this->config['languages'],
  311. $this->config['markUnused']
  312. );
  313. } elseif ($this->config['format'] === 'pot') {
  314. $this->saveMessagesToPOT($messages, $this->config['messagePath'], $catalog);
  315. }
  316. }
  317. /**
  318. * Saves messages to database.
  319. *
  320. * @param array $messages
  321. * @param Connection $db
  322. * @param string $sourceMessageTable
  323. * @param string $messageTable
  324. * @param bool $removeUnused
  325. * @param array $languages
  326. * @param bool $markUnused
  327. */
  328. protected function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages, $markUnused)
  329. {
  330. $currentMessages = [];
  331. $rows = (new Query())->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db);
  332. foreach ($rows as $row) {
  333. $currentMessages[$row['category']][$row['id']] = $row['message'];
  334. }
  335. $currentLanguages = [];
  336. $rows = (new Query())->select(['language'])->from($messageTable)->groupBy('language')->all($db);
  337. foreach ($rows as $row) {
  338. $currentLanguages[] = $row['language'];
  339. }
  340. $missingLanguages = [];
  341. if (!empty($currentLanguages)) {
  342. $missingLanguages = array_diff($languages, $currentLanguages);
  343. }
  344. $new = [];
  345. $obsolete = [];
  346. foreach ($messages as $category => $msgs) {
  347. $msgs = array_unique($msgs);
  348. if (isset($currentMessages[$category])) {
  349. $new[$category] = array_diff($msgs, $currentMessages[$category]);
  350. $obsolete += array_diff($currentMessages[$category], $msgs);
  351. } else {
  352. $new[$category] = $msgs;
  353. }
  354. }
  355. foreach (array_diff(array_keys($currentMessages), array_keys($messages)) as $category) {
  356. $obsolete += $currentMessages[$category];
  357. }
  358. if (!$removeUnused) {
  359. foreach ($obsolete as $pk => $msg) {
  360. if (mb_substr($msg, 0, 2) === '@@' && mb_substr($msg, -2) === '@@') {
  361. unset($obsolete[$pk]);
  362. }
  363. }
  364. }
  365. $obsolete = array_keys($obsolete);
  366. $this->stdout('Inserting new messages...');
  367. $savedFlag = false;
  368. foreach ($new as $category => $msgs) {
  369. foreach ($msgs as $msg) {
  370. $savedFlag = true;
  371. $lastPk = $db->schema->insert($sourceMessageTable, ['category' => $category, 'message' => $msg]);
  372. foreach ($languages as $language) {
  373. $db->createCommand()
  374. ->insert($messageTable, ['id' => $lastPk['id'], 'language' => $language])
  375. ->execute();
  376. }
  377. }
  378. }
  379. if (!empty($missingLanguages)) {
  380. $updatedMessages = [];
  381. $rows = (new Query())->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db);
  382. foreach ($rows as $row) {
  383. $updatedMessages[$row['category']][$row['id']] = $row['message'];
  384. }
  385. foreach ($updatedMessages as $category => $msgs) {
  386. foreach ($msgs as $id => $msg) {
  387. $savedFlag = true;
  388. foreach ($missingLanguages as $language) {
  389. $db->createCommand()
  390. ->insert($messageTable, ['id' => $id, 'language' => $language])
  391. ->execute();
  392. }
  393. }
  394. }
  395. }
  396. $this->stdout($savedFlag ? "saved.\n" : "Nothing to save.\n");
  397. $this->stdout($removeUnused ? 'Deleting obsoleted messages...' : 'Updating obsoleted messages...');
  398. if (empty($obsolete)) {
  399. $this->stdout("Nothing obsoleted...skipped.\n");
  400. return;
  401. }
  402. if ($removeUnused) {
  403. $db->createCommand()
  404. ->delete($sourceMessageTable, ['in', 'id', $obsolete])
  405. ->execute();
  406. $this->stdout("deleted.\n");
  407. } elseif ($markUnused) {
  408. $rows = (new Query())
  409. ->select(['id', 'message'])
  410. ->from($sourceMessageTable)
  411. ->where(['in', 'id', $obsolete])
  412. ->all($db);
  413. foreach ($rows as $row) {
  414. $db->createCommand()->update(
  415. $sourceMessageTable,
  416. ['message' => '@@' . $row['message'] . '@@'],
  417. ['id' => $row['id']]
  418. )->execute();
  419. }
  420. $this->stdout("updated.\n");
  421. } else {
  422. $this->stdout("kept untouched.\n");
  423. }
  424. }
  425. /**
  426. * Extracts messages from a file.
  427. *
  428. * @param string $fileName name of the file to extract messages from
  429. * @param string $translator name of the function used to translate messages
  430. * @param array $ignoreCategories message categories to ignore.
  431. * This parameter is available since version 2.0.4.
  432. * @return array
  433. */
  434. protected function extractMessages($fileName, $translator, $ignoreCategories = [])
  435. {
  436. $this->stdout('Extracting messages from ');
  437. $this->stdout($fileName, Console::FG_CYAN);
  438. $this->stdout("...\n");
  439. $subject = file_get_contents($fileName);
  440. $messages = [];
  441. $tokens = token_get_all($subject);
  442. foreach ((array) $translator as $currentTranslator) {
  443. $translatorTokens = token_get_all('<?php ' . $currentTranslator);
  444. array_shift($translatorTokens);
  445. $messages = array_merge_recursive($messages, $this->extractMessagesFromTokens($tokens, $translatorTokens, $ignoreCategories));
  446. }
  447. $this->stdout("\n");
  448. return $messages;
  449. }
  450. /**
  451. * Extracts messages from a parsed PHP tokens list.
  452. * @param array $tokens tokens to be processed.
  453. * @param array $translatorTokens translator tokens.
  454. * @param array $ignoreCategories message categories to ignore.
  455. * @return array messages.
  456. */
  457. protected function extractMessagesFromTokens(array $tokens, array $translatorTokens, array $ignoreCategories)
  458. {
  459. $messages = [];
  460. $translatorTokensCount = count($translatorTokens);
  461. $matchedTokensCount = 0;
  462. $buffer = [];
  463. $pendingParenthesisCount = 0;
  464. foreach ($tokens as $tokenIndex => $token) {
  465. // finding out translator call
  466. if ($matchedTokensCount < $translatorTokensCount) {
  467. if ($this->tokensEqual($token, $translatorTokens[$matchedTokensCount])) {
  468. $matchedTokensCount++;
  469. } else {
  470. $matchedTokensCount = 0;
  471. }
  472. } elseif ($matchedTokensCount === $translatorTokensCount) {
  473. // translator found
  474. // end of function call
  475. if ($this->tokensEqual(')', $token)) {
  476. $pendingParenthesisCount--;
  477. if ($pendingParenthesisCount === 0) {
  478. // end of translator call or end of something that we can't extract
  479. if (isset($buffer[0][0], $buffer[1], $buffer[2][0]) && $buffer[0][0] === T_CONSTANT_ENCAPSED_STRING && $buffer[1] === ',' && $buffer[2][0] === T_CONSTANT_ENCAPSED_STRING) {
  480. // is valid call we can extract
  481. $category = stripcslashes($buffer[0][1]);
  482. $category = mb_substr($category, 1, -1);
  483. if (!$this->isCategoryIgnored($category, $ignoreCategories)) {
  484. $fullMessage = mb_substr($buffer[2][1], 1, -1);
  485. $i = 3;
  486. while ($i < count($buffer) - 1 && !is_array($buffer[$i]) && $buffer[$i] === '.') {
  487. $fullMessage .= mb_substr($buffer[$i + 1][1], 1, -1);
  488. $i += 2;
  489. }
  490. $message = stripcslashes($fullMessage);
  491. $messages[$category][] = $message;
  492. }
  493. $nestedTokens = array_slice($buffer, 3);
  494. if (count($nestedTokens) > $translatorTokensCount) {
  495. // search for possible nested translator calls
  496. $messages = array_merge_recursive($messages, $this->extractMessagesFromTokens($nestedTokens, $translatorTokens, $ignoreCategories));
  497. }
  498. } else {
  499. // invalid call or dynamic call we can't extract
  500. $line = Console::ansiFormat($this->getLine($buffer), [Console::FG_CYAN]);
  501. $skipping = Console::ansiFormat('Skipping line', [Console::FG_YELLOW]);
  502. $this->stdout("$skipping $line. Make sure both category and message are static strings.\n");
  503. }
  504. // prepare for the next match
  505. $matchedTokensCount = 0;
  506. $pendingParenthesisCount = 0;
  507. $buffer = [];
  508. } else {
  509. $buffer[] = $token;
  510. }
  511. } elseif ($this->tokensEqual('(', $token)) {
  512. // count beginning of function call, skipping translator beginning
  513. // If we are not yet inside the translator, make sure that it's beginning of the real translator.
  514. // See https://github.com/yiisoft/yii2/issues/16828
  515. if ($pendingParenthesisCount === 0) {
  516. $previousTokenIndex = $tokenIndex - $matchedTokensCount - 1;
  517. if (is_array($tokens[$previousTokenIndex])) {
  518. $previousToken = $tokens[$previousTokenIndex][0];
  519. if (in_array($previousToken, [T_OBJECT_OPERATOR, T_PAAMAYIM_NEKUDOTAYIM], true)) {
  520. $matchedTokensCount = 0;
  521. continue;
  522. }
  523. }
  524. }
  525. if ($pendingParenthesisCount > 0) {
  526. $buffer[] = $token;
  527. }
  528. $pendingParenthesisCount++;
  529. } elseif (isset($token[0]) && !in_array($token[0], [T_WHITESPACE, T_COMMENT])) {
  530. // ignore comments and whitespaces
  531. $buffer[] = $token;
  532. }
  533. }
  534. }
  535. return $messages;
  536. }
  537. /**
  538. * The method checks, whether the $category is ignored according to $ignoreCategories array.
  539. *
  540. * Examples:
  541. *
  542. * - `myapp` - will be ignored only `myapp` category;
  543. * - `myapp*` - will be ignored by all categories beginning with `myapp` (`myapp`, `myapplication`, `myapprove`, `myapp/widgets`, `myapp.widgets`, etc).
  544. *
  545. * @param string $category category that is checked
  546. * @param array $ignoreCategories message categories to ignore.
  547. * @return bool
  548. * @since 2.0.7
  549. */
  550. protected function isCategoryIgnored($category, array $ignoreCategories)
  551. {
  552. if (!empty($ignoreCategories)) {
  553. if (in_array($category, $ignoreCategories, true)) {
  554. return true;
  555. }
  556. foreach ($ignoreCategories as $pattern) {
  557. if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
  558. return true;
  559. }
  560. }
  561. }
  562. return false;
  563. }
  564. /**
  565. * Finds out if two PHP tokens are equal.
  566. *
  567. * @param array|string $a
  568. * @param array|string $b
  569. * @return bool
  570. * @since 2.0.1
  571. */
  572. protected function tokensEqual($a, $b)
  573. {
  574. if (is_string($a) && is_string($b)) {
  575. return $a === $b;
  576. }
  577. if (isset($a[0], $a[1], $b[0], $b[1])) {
  578. return $a[0] === $b[0] && $a[1] == $b[1];
  579. }
  580. return false;
  581. }
  582. /**
  583. * Finds out a line of the first non-char PHP token found.
  584. *
  585. * @param array $tokens
  586. * @return int|string
  587. * @since 2.0.1
  588. */
  589. protected function getLine($tokens)
  590. {
  591. foreach ($tokens as $token) {
  592. if (isset($token[2])) {
  593. return $token[2];
  594. }
  595. }
  596. return 'unknown';
  597. }
  598. /**
  599. * Writes messages into PHP files.
  600. *
  601. * @param array $messages
  602. * @param string $dirName name of the directory to write to
  603. * @param bool $overwrite if existing file should be overwritten without backup
  604. * @param bool $removeUnused if obsolete translations should be removed
  605. * @param bool $sort if translations should be sorted
  606. * @param bool $markUnused if obsolete translations should be marked
  607. */
  608. protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)
  609. {
  610. foreach ($messages as $category => $msgs) {
  611. $file = str_replace('\\', '/', "$dirName/$category.php");
  612. $path = dirname($file);
  613. FileHelper::createDirectory($path);
  614. $msgs = array_values(array_unique($msgs));
  615. $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
  616. $this->stdout("Saving messages to $coloredFileName...\n");
  617. $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused);
  618. }
  619. if ($removeUnused) {
  620. $this->deleteUnusedPhpMessageFiles(array_keys($messages), $dirName);
  621. }
  622. }
  623. /**
  624. * Writes category messages into PHP file.
  625. *
  626. * @param array $messages
  627. * @param string $fileName name of the file to write to
  628. * @param bool $overwrite if existing file should be overwritten without backup
  629. * @param bool $removeUnused if obsolete translations should be removed
  630. * @param bool $sort if translations should be sorted
  631. * @param string $category message category
  632. * @param bool $markUnused if obsolete translations should be marked
  633. * @return int exit code
  634. */
  635. protected function saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused)
  636. {
  637. if (is_file($fileName)) {
  638. $rawExistingMessages = require $fileName;
  639. $existingMessages = $rawExistingMessages;
  640. sort($messages);
  641. ksort($existingMessages);
  642. if (array_keys($existingMessages) === $messages && (!$sort || array_keys($rawExistingMessages) === $messages)) {
  643. $this->stdout("Nothing new in \"$category\" category... Nothing to save.\n\n", Console::FG_GREEN);
  644. return ExitCode::OK;
  645. }
  646. unset($rawExistingMessages);
  647. $merged = [];
  648. $untranslated = [];
  649. foreach ($messages as $message) {
  650. if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') {
  651. $merged[$message] = $existingMessages[$message];
  652. } else {
  653. $untranslated[] = $message;
  654. }
  655. }
  656. ksort($merged);
  657. sort($untranslated);
  658. $todo = [];
  659. foreach ($untranslated as $message) {
  660. $todo[$message] = '';
  661. }
  662. ksort($existingMessages);
  663. foreach ($existingMessages as $message => $translation) {
  664. if (!$removeUnused && !isset($merged[$message]) && !isset($todo[$message])) {
  665. if (!$markUnused || (!empty($translation) && (strncmp($translation, '@@', 2) === 0 && substr_compare($translation, '@@', -2, 2) === 0))) {
  666. $todo[$message] = $translation;
  667. } else {
  668. $todo[$message] = '@@' . $translation . '@@';
  669. }
  670. }
  671. }
  672. $merged = array_merge($merged, $todo);
  673. if ($sort) {
  674. ksort($merged);
  675. }
  676. if (false === $overwrite) {
  677. $fileName .= '.merged';
  678. }
  679. $this->stdout("Translation merged.\n");
  680. } else {
  681. $merged = [];
  682. foreach ($messages as $message) {
  683. $merged[$message] = '';
  684. }
  685. ksort($merged);
  686. }
  687. $array = VarDumper::export($merged);
  688. $content = <<<EOD
  689. <?php
  690. {$this->config['phpFileHeader']}{$this->config['phpDocBlock']}
  691. return $array;
  692. EOD;
  693. if (file_put_contents($fileName, $content, LOCK_EX) === false) {
  694. $this->stdout("Translation was NOT saved.\n\n", Console::FG_RED);
  695. return ExitCode::UNSPECIFIED_ERROR;
  696. }
  697. $this->stdout("Translation saved.\n\n", Console::FG_GREEN);
  698. return ExitCode::OK;
  699. }
  700. /**
  701. * Writes messages into PO file.
  702. *
  703. * @param array $messages
  704. * @param string $dirName name of the directory to write to
  705. * @param bool $overwrite if existing file should be overwritten without backup
  706. * @param bool $removeUnused if obsolete translations should be removed
  707. * @param bool $sort if translations should be sorted
  708. * @param string $catalog message catalog
  709. * @param bool $markUnused if obsolete translations should be marked
  710. */
  711. protected function saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused)
  712. {
  713. $file = str_replace('\\', '/', "$dirName/$catalog.po");
  714. FileHelper::createDirectory(dirname($file));
  715. $this->stdout("Saving messages to $file...\n");
  716. $poFile = new GettextPoFile();
  717. $merged = [];
  718. $todos = [];
  719. $hasSomethingToWrite = false;
  720. foreach ($messages as $category => $msgs) {
  721. $notTranslatedYet = [];
  722. $msgs = array_values(array_unique($msgs));
  723. if (is_file($file)) {
  724. $existingMessages = $poFile->load($file, $category);
  725. sort($msgs);
  726. ksort($existingMessages);
  727. if (array_keys($existingMessages) == $msgs) {
  728. $this->stdout("Nothing new in \"$category\" category...\n");
  729. sort($msgs);
  730. foreach ($msgs as $message) {
  731. $merged[$category . chr(4) . $message] = $existingMessages[$message];
  732. }
  733. ksort($merged);
  734. continue;
  735. }
  736. // merge existing message translations with new message translations
  737. foreach ($msgs as $message) {
  738. if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') {
  739. $merged[$category . chr(4) . $message] = $existingMessages[$message];
  740. } else {
  741. $notTranslatedYet[] = $message;
  742. }
  743. }
  744. ksort($merged);
  745. sort($notTranslatedYet);
  746. // collect not yet translated messages
  747. foreach ($notTranslatedYet as $message) {
  748. $todos[$category . chr(4) . $message] = '';
  749. }
  750. // add obsolete unused messages
  751. foreach ($existingMessages as $message => $translation) {
  752. if (!$removeUnused && !isset($merged[$category . chr(4) . $message]) && !isset($todos[$category . chr(4) . $message])) {
  753. if (!$markUnused || (!empty($translation) && (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@'))) {
  754. $todos[$category . chr(4) . $message] = $translation;
  755. } else {
  756. $todos[$category . chr(4) . $message] = '@@' . $translation . '@@';
  757. }
  758. }
  759. }
  760. $merged = array_merge($merged, $todos);
  761. if ($sort) {
  762. ksort($merged);
  763. }
  764. if ($overwrite === false) {
  765. $file .= '.merged';
  766. }
  767. } else {
  768. sort($msgs);
  769. foreach ($msgs as $message) {
  770. $merged[$category . chr(4) . $message] = '';
  771. }
  772. ksort($merged);
  773. }
  774. $this->stdout("Category \"$category\" merged.\n");
  775. $hasSomethingToWrite = true;
  776. }
  777. if ($hasSomethingToWrite) {
  778. $poFile->save($file, $merged);
  779. $this->stdout("Translation saved.\n", Console::FG_GREEN);
  780. } else {
  781. $this->stdout("Nothing to save.\n", Console::FG_GREEN);
  782. }
  783. }
  784. /**
  785. * Writes messages into POT file.
  786. *
  787. * @param array $messages
  788. * @param string $dirName name of the directory to write to
  789. * @param string $catalog message catalog
  790. * @since 2.0.6
  791. */
  792. protected function saveMessagesToPOT($messages, $dirName, $catalog)
  793. {
  794. $file = str_replace('\\', '/', "$dirName/$catalog.pot");
  795. FileHelper::createDirectory(dirname($file));
  796. $this->stdout("Saving messages to $file...\n");
  797. $poFile = new GettextPoFile();
  798. $merged = [];
  799. $hasSomethingToWrite = false;
  800. foreach ($messages as $category => $msgs) {
  801. $msgs = array_values(array_unique($msgs));
  802. sort($msgs);
  803. foreach ($msgs as $message) {
  804. $merged[$category . chr(4) . $message] = '';
  805. }
  806. $this->stdout("Category \"$category\" merged.\n");
  807. $hasSomethingToWrite = true;
  808. }
  809. if ($hasSomethingToWrite) {
  810. ksort($merged);
  811. $poFile->save($file, $merged);
  812. $this->stdout("Translation saved.\n", Console::FG_GREEN);
  813. } else {
  814. $this->stdout("Nothing to save.\n", Console::FG_GREEN);
  815. }
  816. }
  817. private function deleteUnusedPhpMessageFiles($existingCategories, $dirName)
  818. {
  819. $messageFiles = FileHelper::findFiles($dirName);
  820. foreach ($messageFiles as $messageFile) {
  821. $categoryFileName = str_replace($dirName, '', $messageFile);
  822. $categoryFileName = ltrim($categoryFileName, DIRECTORY_SEPARATOR);
  823. $category = preg_replace('#\.php$#', '', $categoryFileName);
  824. $category = str_replace(DIRECTORY_SEPARATOR, '/', $category);
  825. if (!in_array($category, $existingCategories, true)) {
  826. unlink($messageFile);
  827. }
  828. }
  829. }
  830. /**
  831. * @param string $configFile
  832. * @throws Exception If configuration file does not exists.
  833. * @since 2.0.13
  834. */
  835. protected function initConfig($configFile)
  836. {
  837. $configFileContent = [];
  838. if ($configFile !== null) {
  839. $configFile = Yii::getAlias($configFile);
  840. if (!is_file($configFile)) {
  841. throw new Exception("The configuration file does not exist: $configFile");
  842. }
  843. $configFileContent = require $configFile;
  844. }
  845. $this->config = array_merge(
  846. $this->getOptionValues($this->action->id),
  847. $configFileContent,
  848. $this->getPassedOptionValues()
  849. );
  850. $this->config['sourcePath'] = Yii::getAlias($this->config['sourcePath']);
  851. $this->config['messagePath'] = Yii::getAlias($this->config['messagePath']);
  852. if (!isset($this->config['sourcePath'], $this->config['languages'])) {
  853. throw new Exception('The configuration file must specify "sourcePath" and "languages".');
  854. }
  855. if (!is_dir($this->config['sourcePath'])) {
  856. throw new Exception("The source path {$this->config['sourcePath']} is not a valid directory.");
  857. }
  858. if (empty($this->config['format']) || !in_array($this->config['format'], ['php', 'po', 'pot', 'db'])) {
  859. throw new Exception('Format should be either "php", "po", "pot" or "db".');
  860. }
  861. if (in_array($this->config['format'], ['php', 'po', 'pot'])) {
  862. if (!isset($this->config['messagePath'])) {
  863. throw new Exception('The configuration file must specify "messagePath".');
  864. }
  865. if (!is_dir($this->config['messagePath'])) {
  866. throw new Exception("The message path {$this->config['messagePath']} is not a valid directory.");
  867. }
  868. }
  869. if (empty($this->config['languages'])) {
  870. throw new Exception('Languages cannot be empty.');
  871. }
  872. if ($this->config['format'] === 'php' && $this->config['phpDocBlock'] === null) {
  873. $this->config['phpDocBlock'] = <<<DOCBLOCK
  874. /**
  875. * Message translations.
  876. *
  877. * This file is automatically generated by 'yii {$this->id}/{$this->action->id}' command.
  878. * It contains the localizable messages extracted from source code.
  879. * You may modify this file by translating the extracted messages.
  880. *
  881. * Each array element represents the translation (value) of a message (key).
  882. * If the value is empty, the message is considered as not translated.
  883. * Messages that no longer need translation will have their translations
  884. * enclosed between a pair of '@@' marks.
  885. *
  886. * Message string can be used with plural forms format. Check i18n section
  887. * of the guide for details.
  888. *
  889. * NOTE: this file must be saved in UTF-8 encoding.
  890. */
  891. DOCBLOCK;
  892. }
  893. }
  894. }