PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php

https://gitlab.com/Isaki/le331.fr
PHP | 268 lines | 190 code | 48 blank | 30 comment | 28 complexity | f91350e847314d1248a2f0389d6e563b MD5 | raw file
  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\Component\Console\Style\SymfonyStyle;
  12. use Symfony\Component\Translation\Catalogue\MergeOperation;
  13. use Symfony\Component\Console\Input\InputInterface;
  14. use Symfony\Component\Console\Output\OutputInterface;
  15. use Symfony\Component\Console\Input\InputArgument;
  16. use Symfony\Component\Console\Input\InputOption;
  17. use Symfony\Component\Translation\MessageCatalogue;
  18. use Symfony\Component\Translation\Translator;
  19. /**
  20. * Helps finding unused or missing translation messages in a given locale
  21. * and comparing them with the fallback ones.
  22. *
  23. * @author Florian Voutzinos <florian@voutzinos.com>
  24. */
  25. class TranslationDebugCommand extends ContainerAwareCommand
  26. {
  27. const MESSAGE_MISSING = 0;
  28. const MESSAGE_UNUSED = 1;
  29. const MESSAGE_EQUALS_FALLBACK = 2;
  30. /**
  31. * {@inheritdoc}
  32. */
  33. protected function configure()
  34. {
  35. $this
  36. ->setName('debug:translation')
  37. ->setAliases(array(
  38. 'translation:debug',
  39. ))
  40. ->setDefinition(array(
  41. new InputArgument('locale', InputArgument::REQUIRED, 'The locale'),
  42. new InputArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages, defaults to app/Resources folder'),
  43. new InputOption('domain', null, InputOption::VALUE_OPTIONAL, 'The messages domain'),
  44. new InputOption('only-missing', null, InputOption::VALUE_NONE, 'Displays only missing messages'),
  45. new InputOption('only-unused', null, InputOption::VALUE_NONE, 'Displays only unused messages'),
  46. ))
  47. ->setDescription('Displays translation messages information')
  48. ->setHelp(<<<EOF
  49. The <info>%command.name%</info> command helps finding unused or missing translation
  50. messages and comparing them with the fallback ones by inspecting the
  51. templates and translation files of a given bundle or the app folder.
  52. You can display information about bundle translations in a specific locale:
  53. <info>php %command.full_name% en AcmeDemoBundle</info>
  54. You can also specify a translation domain for the search:
  55. <info>php %command.full_name% --domain=messages en AcmeDemoBundle</info>
  56. You can only display missing messages:
  57. <info>php %command.full_name% --only-missing en AcmeDemoBundle</info>
  58. You can only display unused messages:
  59. <info>php %command.full_name% --only-unused en AcmeDemoBundle</info>
  60. You can display information about app translations in a specific locale:
  61. <info>php %command.full_name% en</info>
  62. EOF
  63. )
  64. ;
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. protected function execute(InputInterface $input, OutputInterface $output)
  70. {
  71. $output = new SymfonyStyle($input, $output);
  72. if (false !== strpos($input->getFirstArgument(), ':d')) {
  73. $output->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.');
  74. }
  75. $locale = $input->getArgument('locale');
  76. $domain = $input->getOption('domain');
  77. $loader = $this->getContainer()->get('translation.loader');
  78. $kernel = $this->getContainer()->get('kernel');
  79. // Define Root Path to App folder
  80. $transPaths = array($kernel->getRootDir().'/Resources/');
  81. // Override with provided Bundle info
  82. if (null !== $input->getArgument('bundle')) {
  83. try {
  84. $bundle = $kernel->getBundle($input->getArgument('bundle'));
  85. $transPaths = array(
  86. $bundle->getPath().'/Resources/',
  87. sprintf('%s/Resources/%s/', $kernel->getRootDir(), $bundle->getName()),
  88. );
  89. } catch (\InvalidArgumentException $e) {
  90. // such a bundle does not exist, so treat the argument as path
  91. $transPaths = array($input->getArgument('bundle').'/Resources/');
  92. if (!is_dir($transPaths[0])) {
  93. throw new \InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $transPaths[0]));
  94. }
  95. }
  96. }
  97. // Extract used messages
  98. $extractedCatalogue = new MessageCatalogue($locale);
  99. foreach ($transPaths as $path) {
  100. $path .= 'views';
  101. if (is_dir($path)) {
  102. $this->getContainer()->get('translation.extractor')->extract($path, $extractedCatalogue);
  103. }
  104. }
  105. // Load defined messages
  106. $currentCatalogue = new MessageCatalogue($locale);
  107. foreach ($transPaths as $path) {
  108. $path .= 'translations';
  109. if (is_dir($path)) {
  110. $loader->loadMessages($path, $currentCatalogue);
  111. }
  112. }
  113. // Merge defined and extracted messages to get all message ids
  114. $mergeOperation = new MergeOperation($extractedCatalogue, $currentCatalogue);
  115. $allMessages = $mergeOperation->getResult()->all($domain);
  116. if (null !== $domain) {
  117. $allMessages = array($domain => $allMessages);
  118. }
  119. // No defined or extracted messages
  120. if (empty($allMessages) || null !== $domain && empty($allMessages[$domain])) {
  121. $outputMessage = sprintf('No defined or extracted messages for locale "%s"', $locale);
  122. if (null !== $domain) {
  123. $outputMessage .= sprintf(' and domain "%s"', $domain);
  124. }
  125. $output->warning($outputMessage);
  126. return;
  127. }
  128. // Load the fallback catalogues
  129. $fallbackCatalogues = array();
  130. $translator = $this->getContainer()->get('translator');
  131. if ($translator instanceof Translator) {
  132. foreach ($translator->getFallbackLocales() as $fallbackLocale) {
  133. if ($fallbackLocale === $locale) {
  134. continue;
  135. }
  136. $fallbackCatalogue = new MessageCatalogue($fallbackLocale);
  137. foreach ($transPaths as $path) {
  138. $path = $path.'translations';
  139. if (is_dir($path)) {
  140. $loader->loadMessages($path, $fallbackCatalogue);
  141. }
  142. }
  143. $fallbackCatalogues[] = $fallbackCatalogue;
  144. }
  145. }
  146. // Display header line
  147. $headers = array('State', 'Domain', 'Id', sprintf('Message Preview (%s)', $locale));
  148. foreach ($fallbackCatalogues as $fallbackCatalogue) {
  149. $headers[] = sprintf('Fallback Message Preview (%s)', $fallbackCatalogue->getLocale());
  150. }
  151. $rows = array();
  152. // Iterate all message ids and determine their state
  153. foreach ($allMessages as $domain => $messages) {
  154. foreach (array_keys($messages) as $messageId) {
  155. $value = $currentCatalogue->get($messageId, $domain);
  156. $states = array();
  157. if ($extractedCatalogue->defines($messageId, $domain)) {
  158. if (!$currentCatalogue->defines($messageId, $domain)) {
  159. $states[] = self::MESSAGE_MISSING;
  160. }
  161. } elseif ($currentCatalogue->defines($messageId, $domain)) {
  162. $states[] = self::MESSAGE_UNUSED;
  163. }
  164. if (!in_array(self::MESSAGE_UNUSED, $states) && true === $input->getOption('only-unused')
  165. || !in_array(self::MESSAGE_MISSING, $states) && true === $input->getOption('only-missing')) {
  166. continue;
  167. }
  168. foreach ($fallbackCatalogues as $fallbackCatalogue) {
  169. if ($fallbackCatalogue->defines($messageId, $domain) && $value === $fallbackCatalogue->get($messageId, $domain)) {
  170. $states[] = self::MESSAGE_EQUALS_FALLBACK;
  171. break;
  172. }
  173. }
  174. $row = array($this->formatStates($states), $domain, $this->formatId($messageId), $this->sanitizeString($value));
  175. foreach ($fallbackCatalogues as $fallbackCatalogue) {
  176. $row[] = $this->sanitizeString($fallbackCatalogue->get($messageId, $domain));
  177. }
  178. $rows[] = $row;
  179. }
  180. }
  181. $output->table($headers, $rows);
  182. }
  183. private function formatState($state)
  184. {
  185. if (self::MESSAGE_MISSING === $state) {
  186. return '<error>missing</error>';
  187. }
  188. if (self::MESSAGE_UNUSED === $state) {
  189. return '<comment>unused</comment>';
  190. }
  191. if (self::MESSAGE_EQUALS_FALLBACK === $state) {
  192. return '<info>fallback</info>';
  193. }
  194. return $state;
  195. }
  196. private function formatStates(array $states)
  197. {
  198. $result = array();
  199. foreach ($states as $state) {
  200. $result[] = $this->formatState($state);
  201. }
  202. return implode(' ', $result);
  203. }
  204. private function formatId($id)
  205. {
  206. return sprintf('<fg=cyan;options=bold>%s</fg=cyan;options=bold>', $id);
  207. }
  208. private function sanitizeString($string, $length = 40)
  209. {
  210. $string = trim(preg_replace('/\s+/', ' ', $string));
  211. if (function_exists('mb_strlen') && false !== $encoding = mb_detect_encoding($string)) {
  212. if (mb_strlen($string, $encoding) > $length) {
  213. return mb_substr($string, 0, $length - 3, $encoding).'...';
  214. }
  215. } elseif (strlen($string) > $length) {
  216. return substr($string, 0, $length - 3).'...';
  217. }
  218. return $string;
  219. }
  220. }