TranslationDebugCommand.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bundle\FrameworkBundle\Command;
  11. use Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader;
  12. use Symfony\Component\Console\Input\InputArgument;
  13. use Symfony\Component\Console\Input\InputInterface;
  14. use Symfony\Component\Console\Input\InputOption;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. use Symfony\Component\Console\Style\SymfonyStyle;
  17. use Symfony\Component\HttpKernel\Kernel;
  18. use Symfony\Component\Translation\Catalogue\MergeOperation;
  19. use Symfony\Component\Translation\DataCollectorTranslator;
  20. use Symfony\Component\Translation\LoggingTranslator;
  21. use Symfony\Component\Translation\MessageCatalogue;
  22. use Symfony\Component\Translation\Translator;
  23. /**
  24. * Helps finding unused or missing translation messages in a given locale
  25. * and comparing them with the fallback ones.
  26. *
  27. * @author Florian Voutzinos <florian@voutzinos.com>
  28. */
  29. class TranslationDebugCommand extends ContainerAwareCommand
  30. {
  31. const MESSAGE_MISSING = 0;
  32. const MESSAGE_UNUSED = 1;
  33. const MESSAGE_EQUALS_FALLBACK = 2;
  34. /**
  35. * {@inheritdoc}
  36. */
  37. protected function configure()
  38. {
  39. $this
  40. ->setName('debug:translation')
  41. ->setAliases(array(
  42. 'translation:debug',
  43. ))
  44. ->setDefinition(array(
  45. new InputArgument('locale', InputArgument::REQUIRED, 'The locale'),
  46. new InputArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages, defaults to app/Resources folder'),
  47. new InputOption('domain', null, InputOption::VALUE_OPTIONAL, 'The messages domain'),
  48. new InputOption('only-missing', null, InputOption::VALUE_NONE, 'Displays only missing messages'),
  49. new InputOption('only-unused', null, InputOption::VALUE_NONE, 'Displays only unused messages'),
  50. new InputOption('all', null, InputOption::VALUE_NONE, 'Load messages from all registered bundles'),
  51. ))
  52. ->setDescription('Displays translation messages information')
  53. ->setHelp(<<<'EOF'
  54. The <info>%command.name%</info> command helps finding unused or missing translation
  55. messages and comparing them with the fallback ones by inspecting the
  56. templates and translation files of a given bundle or the app folder.
  57. You can display information about bundle translations in a specific locale:
  58. <info>php %command.full_name% en AcmeDemoBundle</info>
  59. You can also specify a translation domain for the search:
  60. <info>php %command.full_name% --domain=messages en AcmeDemoBundle</info>
  61. You can only display missing messages:
  62. <info>php %command.full_name% --only-missing en AcmeDemoBundle</info>
  63. You can only display unused messages:
  64. <info>php %command.full_name% --only-unused en AcmeDemoBundle</info>
  65. You can display information about app translations in a specific locale:
  66. <info>php %command.full_name% en</info>
  67. You can display information about translations in all registered bundles in a specific locale:
  68. <info>php %command.full_name% --all en</info>
  69. EOF
  70. )
  71. ;
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. protected function execute(InputInterface $input, OutputInterface $output)
  77. {
  78. $io = new SymfonyStyle($input, $output);
  79. if (false !== strpos($input->getFirstArgument(), ':d')) {
  80. $io->caution('The use of "translation:debug" command is deprecated since version 2.7 and will be removed in 3.0. Use the "debug:translation" instead.');
  81. }
  82. $locale = $input->getArgument('locale');
  83. $domain = $input->getOption('domain');
  84. /** @var TranslationLoader $loader */
  85. $loader = $this->getContainer()->get('translation.loader');
  86. /** @var Kernel $kernel */
  87. $kernel = $this->getContainer()->get('kernel');
  88. // Define Root Path to App folder
  89. $transPaths = array($kernel->getRootDir().'/Resources/');
  90. // Override with provided Bundle info
  91. if (null !== $input->getArgument('bundle')) {
  92. try {
  93. $bundle = $kernel->getBundle($input->getArgument('bundle'));
  94. $transPaths = array(
  95. $bundle->getPath().'/Resources/',
  96. sprintf('%s/Resources/%s/', $kernel->getRootDir(), $bundle->getName()),
  97. );
  98. } catch (\InvalidArgumentException $e) {
  99. // such a bundle does not exist, so treat the argument as path
  100. $transPaths = array($input->getArgument('bundle').'/Resources/');
  101. if (!is_dir($transPaths[0])) {
  102. throw new \InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $transPaths[0]));
  103. }
  104. }
  105. } elseif ($input->getOption('all')) {
  106. foreach ($kernel->getBundles() as $bundle) {
  107. $transPaths[] = $bundle->getPath().'/Resources/';
  108. $transPaths[] = sprintf('%s/Resources/%s/', $kernel->getRootDir(), $bundle->getName());
  109. }
  110. }
  111. // Extract used messages
  112. $extractedCatalogue = $this->extractMessages($locale, $transPaths);
  113. // Load defined messages
  114. $currentCatalogue = $this->loadCurrentMessages($locale, $transPaths, $loader);
  115. // Merge defined and extracted messages to get all message ids
  116. $mergeOperation = new MergeOperation($extractedCatalogue, $currentCatalogue);
  117. $allMessages = $mergeOperation->getResult()->all($domain);
  118. if (null !== $domain) {
  119. $allMessages = array($domain => $allMessages);
  120. }
  121. // No defined or extracted messages
  122. if (empty($allMessages) || null !== $domain && empty($allMessages[$domain])) {
  123. $outputMessage = sprintf('No defined or extracted messages for locale "%s"', $locale);
  124. if (null !== $domain) {
  125. $outputMessage .= sprintf(' and domain "%s"', $domain);
  126. }
  127. $io->warning($outputMessage);
  128. return;
  129. }
  130. // Load the fallback catalogues
  131. $fallbackCatalogues = $this->loadFallbackCatalogues($locale, $transPaths, $loader);
  132. // Display header line
  133. $headers = array('State', 'Domain', 'Id', sprintf('Message Preview (%s)', $locale));
  134. foreach ($fallbackCatalogues as $fallbackCatalogue) {
  135. $headers[] = sprintf('Fallback Message Preview (%s)', $fallbackCatalogue->getLocale());
  136. }
  137. $rows = array();
  138. // Iterate all message ids and determine their state
  139. foreach ($allMessages as $domain => $messages) {
  140. foreach (array_keys($messages) as $messageId) {
  141. $value = $currentCatalogue->get($messageId, $domain);
  142. $states = array();
  143. if ($extractedCatalogue->defines($messageId, $domain)) {
  144. if (!$currentCatalogue->defines($messageId, $domain)) {
  145. $states[] = self::MESSAGE_MISSING;
  146. }
  147. } elseif ($currentCatalogue->defines($messageId, $domain)) {
  148. $states[] = self::MESSAGE_UNUSED;
  149. }
  150. if (!\in_array(self::MESSAGE_UNUSED, $states) && true === $input->getOption('only-unused')
  151. || !\in_array(self::MESSAGE_MISSING, $states) && true === $input->getOption('only-missing')) {
  152. continue;
  153. }
  154. foreach ($fallbackCatalogues as $fallbackCatalogue) {
  155. if ($fallbackCatalogue->defines($messageId, $domain) && $value === $fallbackCatalogue->get($messageId, $domain)) {
  156. $states[] = self::MESSAGE_EQUALS_FALLBACK;
  157. break;
  158. }
  159. }
  160. $row = array($this->formatStates($states), $domain, $this->formatId($messageId), $this->sanitizeString($value));
  161. foreach ($fallbackCatalogues as $fallbackCatalogue) {
  162. $row[] = $this->sanitizeString($fallbackCatalogue->get($messageId, $domain));
  163. }
  164. $rows[] = $row;
  165. }
  166. }
  167. $io->table($headers, $rows);
  168. }
  169. private function formatState($state)
  170. {
  171. if (self::MESSAGE_MISSING === $state) {
  172. return '<error> missing </error>';
  173. }
  174. if (self::MESSAGE_UNUSED === $state) {
  175. return '<comment> unused </comment>';
  176. }
  177. if (self::MESSAGE_EQUALS_FALLBACK === $state) {
  178. return '<info> fallback </info>';
  179. }
  180. return $state;
  181. }
  182. private function formatStates(array $states)
  183. {
  184. $result = array();
  185. foreach ($states as $state) {
  186. $result[] = $this->formatState($state);
  187. }
  188. return implode(' ', $result);
  189. }
  190. private function formatId($id)
  191. {
  192. return sprintf('<fg=cyan;options=bold>%s</>', $id);
  193. }
  194. private function sanitizeString($string, $length = 40)
  195. {
  196. $string = trim(preg_replace('/\s+/', ' ', $string));
  197. if (false !== $encoding = mb_detect_encoding($string, null, true)) {
  198. if (mb_strlen($string, $encoding) > $length) {
  199. return mb_substr($string, 0, $length - 3, $encoding).'...';
  200. }
  201. } elseif (\strlen($string) > $length) {
  202. return substr($string, 0, $length - 3).'...';
  203. }
  204. return $string;
  205. }
  206. /**
  207. * @param string $locale
  208. * @param array $transPaths
  209. *
  210. * @return MessageCatalogue
  211. */
  212. private function extractMessages($locale, $transPaths)
  213. {
  214. $extractedCatalogue = new MessageCatalogue($locale);
  215. foreach ($transPaths as $path) {
  216. $path .= 'views';
  217. if (is_dir($path)) {
  218. $this->getContainer()->get('translation.extractor')->extract($path, $extractedCatalogue);
  219. }
  220. }
  221. return $extractedCatalogue;
  222. }
  223. /**
  224. * @param string $locale
  225. * @param array $transPaths
  226. * @param TranslationLoader $loader
  227. *
  228. * @return MessageCatalogue
  229. */
  230. private function loadCurrentMessages($locale, $transPaths, TranslationLoader $loader)
  231. {
  232. $currentCatalogue = new MessageCatalogue($locale);
  233. foreach ($transPaths as $path) {
  234. $path .= 'translations';
  235. if (is_dir($path)) {
  236. $loader->loadMessages($path, $currentCatalogue);
  237. }
  238. }
  239. return $currentCatalogue;
  240. }
  241. /**
  242. * @param string $locale
  243. * @param array $transPaths
  244. * @param TranslationLoader $loader
  245. *
  246. * @return MessageCatalogue[]
  247. */
  248. private function loadFallbackCatalogues($locale, $transPaths, TranslationLoader $loader)
  249. {
  250. $fallbackCatalogues = array();
  251. $translator = $this->getContainer()->get('translator');
  252. if ($translator instanceof Translator || $translator instanceof DataCollectorTranslator || $translator instanceof LoggingTranslator) {
  253. foreach ($translator->getFallbackLocales() as $fallbackLocale) {
  254. if ($fallbackLocale === $locale) {
  255. continue;
  256. }
  257. $fallbackCatalogue = new MessageCatalogue($fallbackLocale);
  258. foreach ($transPaths as $path) {
  259. $path .= 'translations';
  260. if (is_dir($path)) {
  261. $loader->loadMessages($path, $fallbackCatalogue);
  262. }
  263. }
  264. $fallbackCatalogues[] = $fallbackCatalogue;
  265. }
  266. }
  267. return $fallbackCatalogues;
  268. }
  269. }