vendor/symfony/framework-bundle/Command/TranslationUpdateCommand.php line 64

Open in your IDE?
  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\Command\Command;
  12. use Symfony\Component\Console\Completion\CompletionInput;
  13. use Symfony\Component\Console\Completion\CompletionSuggestions;
  14. use Symfony\Component\Console\Exception\InvalidArgumentException;
  15. use Symfony\Component\Console\Input\InputArgument;
  16. use Symfony\Component\Console\Input\InputInterface;
  17. use Symfony\Component\Console\Input\InputOption;
  18. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  19. use Symfony\Component\Console\Output\OutputInterface;
  20. use Symfony\Component\Console\Style\SymfonyStyle;
  21. use Symfony\Component\HttpKernel\KernelInterface;
  22. use Symfony\Component\Translation\Catalogue\MergeOperation;
  23. use Symfony\Component\Translation\Catalogue\TargetOperation;
  24. use Symfony\Component\Translation\Extractor\ExtractorInterface;
  25. use Symfony\Component\Translation\MessageCatalogue;
  26. use Symfony\Component\Translation\MessageCatalogueInterface;
  27. use Symfony\Component\Translation\Reader\TranslationReaderInterface;
  28. use Symfony\Component\Translation\Writer\TranslationWriterInterface;
  29. /**
  30.  * A command that parses templates to extract translation messages and adds them
  31.  * into the translation files.
  32.  *
  33.  * @author Michel Salib <michelsalib@hotmail.com>
  34.  *
  35.  * @final
  36.  */
  37. class TranslationUpdateCommand extends Command
  38. {
  39.     private const ASC 'asc';
  40.     private const DESC 'desc';
  41.     private const SORT_ORDERS = [self::ASCself::DESC];
  42.     private const FORMATS = [
  43.         'xlf12' => ['xlf''1.2'],
  44.         'xlf20' => ['xlf''2.0'],
  45.     ];
  46.     protected static $defaultName 'translation:extract|translation:update';
  47.     protected static $defaultDescription 'Extract missing translations keys from code to translation files.';
  48.     private $writer;
  49.     private $reader;
  50.     private $extractor;
  51.     private $defaultLocale;
  52.     private $defaultTransPath;
  53.     private $defaultViewsPath;
  54.     private $transPaths;
  55.     private $codePaths;
  56.     private $enabledLocales;
  57.     public function __construct(TranslationWriterInterface $writerTranslationReaderInterface $readerExtractorInterface $extractorstring $defaultLocalestring $defaultTransPath nullstring $defaultViewsPath null, array $transPaths = [], array $codePaths = [], array $enabledLocales = [])
  58.     {
  59.         parent::__construct();
  60.         $this->writer $writer;
  61.         $this->reader $reader;
  62.         $this->extractor $extractor;
  63.         $this->defaultLocale $defaultLocale;
  64.         $this->defaultTransPath $defaultTransPath;
  65.         $this->defaultViewsPath $defaultViewsPath;
  66.         $this->transPaths $transPaths;
  67.         $this->codePaths $codePaths;
  68.         $this->enabledLocales $enabledLocales;
  69.     }
  70.     /**
  71.      * {@inheritdoc}
  72.      */
  73.     protected function configure()
  74.     {
  75.         $this
  76.             ->setDefinition([
  77.                 new InputArgument('locale'InputArgument::REQUIRED'The locale'),
  78.                 new InputArgument('bundle'InputArgument::OPTIONAL'The bundle name or directory where to load the messages'),
  79.                 new InputOption('prefix'nullInputOption::VALUE_OPTIONAL'Override the default prefix''__'),
  80.                 new InputOption('output-format'nullInputOption::VALUE_OPTIONAL'Override the default output format (deprecated)'),
  81.                 new InputOption('format'nullInputOption::VALUE_OPTIONAL'Override the default output format''xlf12'),
  82.                 new InputOption('dump-messages'nullInputOption::VALUE_NONE'Should the messages be dumped in the console'),
  83.                 new InputOption('force'nullInputOption::VALUE_NONE'Should the extract be done'),
  84.                 new InputOption('clean'nullInputOption::VALUE_NONE'Should clean not found messages'),
  85.                 new InputOption('domain'nullInputOption::VALUE_OPTIONAL'Specify the domain to extract'),
  86.                 new InputOption('xliff-version'nullInputOption::VALUE_OPTIONAL'Override the default xliff version (deprecated)'),
  87.                 new InputOption('sort'nullInputOption::VALUE_OPTIONAL'Return list of messages sorted alphabetically''asc'),
  88.                 new InputOption('as-tree'nullInputOption::VALUE_OPTIONAL'Dump the messages as a tree-like structure: The given value defines the level where to switch to inline YAML'),
  89.             ])
  90.             ->setDescription(self::$defaultDescription)
  91.             ->setHelp(<<<'EOF'
  92. The <info>%command.name%</info> command extracts translation strings from templates
  93. of a given bundle or the default translations directory. It can display them or merge
  94. the new ones into the translation files.
  95. When new translation strings are found it can automatically add a prefix to the translation
  96. message.
  97. Example running against a Bundle (AcmeBundle)
  98.   <info>php %command.full_name% --dump-messages en AcmeBundle</info>
  99.   <info>php %command.full_name% --force --prefix="new_" fr AcmeBundle</info>
  100. Example running against default messages directory
  101.   <info>php %command.full_name% --dump-messages en</info>
  102.   <info>php %command.full_name% --force --prefix="new_" fr</info>
  103. You can sort the output with the <comment>--sort</> flag:
  104.     <info>php %command.full_name% --dump-messages --sort=asc en AcmeBundle</info>
  105.     <info>php %command.full_name% --dump-messages --sort=desc fr</info>
  106. You can dump a tree-like structure using the yaml format with <comment>--as-tree</> flag:
  107.     <info>php %command.full_name% --force --format=yaml --as-tree=3 en AcmeBundle</info>
  108.     <info>php %command.full_name% --force --format=yaml --sort=asc --as-tree=3 fr</info>
  109. EOF
  110.             )
  111.         ;
  112.     }
  113.     /**
  114.      * {@inheritdoc}
  115.      */
  116.     protected function execute(InputInterface $inputOutputInterface $output): int
  117.     {
  118.         $io = new SymfonyStyle($input$output);
  119.         $errorIo $output instanceof ConsoleOutputInterface ? new SymfonyStyle($input$output->getErrorOutput()) : $io;
  120.         if ('translation:update' === $input->getFirstArgument()) {
  121.             $errorIo->caution('Command "translation:update" is deprecated since version 5.4 and will be removed in Symfony 6.0. Use "translation:extract" instead.');
  122.         }
  123.         $io = new SymfonyStyle($input$output);
  124.         $errorIo $io->getErrorStyle();
  125.         // check presence of force or dump-message
  126.         if (true !== $input->getOption('force') && true !== $input->getOption('dump-messages')) {
  127.             $errorIo->error('You must choose one of --force or --dump-messages');
  128.             return 1;
  129.         }
  130.         $format $input->getOption('output-format') ?: $input->getOption('format');
  131.         $xliffVersion $input->getOption('xliff-version') ?? '1.2';
  132.         if ($input->getOption('xliff-version')) {
  133.             $errorIo->warning(sprintf('The "--xliff-version" option is deprecated since version 5.3, use "--format=xlf%d" instead.'10 $xliffVersion));
  134.         }
  135.         if ($input->getOption('output-format')) {
  136.             $errorIo->warning(sprintf('The "--output-format" option is deprecated since version 5.3, use "--format=xlf%d" instead.'10 $xliffVersion));
  137.         }
  138.         if (\in_array($formatarray_keys(self::FORMATS), true)) {
  139.             [$format$xliffVersion] = self::FORMATS[$format];
  140.         }
  141.         // check format
  142.         $supportedFormats $this->writer->getFormats();
  143.         if (!\in_array($format$supportedFormatstrue)) {
  144.             $errorIo->error(['Wrong output format''Supported formats are: '.implode(', '$supportedFormats).', xlf12 and xlf20.']);
  145.             return 1;
  146.         }
  147.         /** @var KernelInterface $kernel */
  148.         $kernel $this->getApplication()->getKernel();
  149.         // Define Root Paths
  150.         $transPaths $this->getRootTransPaths();
  151.         $codePaths $this->getRootCodePaths($kernel);
  152.         $currentName 'default directory';
  153.         // Override with provided Bundle info
  154.         if (null !== $input->getArgument('bundle')) {
  155.             try {
  156.                 $foundBundle $kernel->getBundle($input->getArgument('bundle'));
  157.                 $bundleDir $foundBundle->getPath();
  158.                 $transPaths = [is_dir($bundleDir.'/Resources/translations') ? $bundleDir.'/Resources/translations' $bundleDir.'/translations'];
  159.                 $codePaths = [is_dir($bundleDir.'/Resources/views') ? $bundleDir.'/Resources/views' $bundleDir.'/templates'];
  160.                 if ($this->defaultTransPath) {
  161.                     $transPaths[] = $this->defaultTransPath;
  162.                 }
  163.                 if ($this->defaultViewsPath) {
  164.                     $codePaths[] = $this->defaultViewsPath;
  165.                 }
  166.                 $currentName $foundBundle->getName();
  167.             } catch (\InvalidArgumentException $e) {
  168.                 // such a bundle does not exist, so treat the argument as path
  169.                 $path $input->getArgument('bundle');
  170.                 $transPaths = [$path.'/translations'];
  171.                 $codePaths = [$path.'/templates'];
  172.                 if (!is_dir($transPaths[0])) {
  173.                     throw new InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.'$transPaths[0]));
  174.                 }
  175.             }
  176.         }
  177.         $io->title('Translation Messages Extractor and Dumper');
  178.         $io->comment(sprintf('Generating "<info>%s</info>" translation files for "<info>%s</info>"'$input->getArgument('locale'), $currentName));
  179.         $io->comment('Parsing templates...');
  180.         $extractedCatalogue $this->extractMessages($input->getArgument('locale'), $codePaths$input->getOption('prefix'));
  181.         $io->comment('Loading translation files...');
  182.         $currentCatalogue $this->loadCurrentMessages($input->getArgument('locale'), $transPaths);
  183.         if (null !== $domain $input->getOption('domain')) {
  184.             $currentCatalogue $this->filterCatalogue($currentCatalogue$domain);
  185.             $extractedCatalogue $this->filterCatalogue($extractedCatalogue$domain);
  186.         }
  187.         // process catalogues
  188.         $operation $input->getOption('clean')
  189.             ? new TargetOperation($currentCatalogue$extractedCatalogue)
  190.             : new MergeOperation($currentCatalogue$extractedCatalogue);
  191.         // Exit if no messages found.
  192.         if (!\count($operation->getDomains())) {
  193.             $errorIo->warning('No translation messages were found.');
  194.             return 0;
  195.         }
  196.         $resultMessage 'Translation files were successfully updated';
  197.         $operation->moveMessagesToIntlDomainsIfPossible('new');
  198.         // show compiled list of messages
  199.         if (true === $input->getOption('dump-messages')) {
  200.             $extractedMessagesCount 0;
  201.             $io->newLine();
  202.             foreach ($operation->getDomains() as $domain) {
  203.                 $newKeys array_keys($operation->getNewMessages($domain));
  204.                 $allKeys array_keys($operation->getMessages($domain));
  205.                 $list array_merge(
  206.                     array_diff($allKeys$newKeys),
  207.                     array_map(function ($id) {
  208.                         return sprintf('<fg=green>%s</>'$id);
  209.                     }, $newKeys),
  210.                     array_map(function ($id) {
  211.                         return sprintf('<fg=red>%s</>'$id);
  212.                     }, array_keys($operation->getObsoleteMessages($domain)))
  213.                 );
  214.                 $domainMessagesCount \count($list);
  215.                 if ($sort $input->getOption('sort')) {
  216.                     $sort strtolower($sort);
  217.                     if (!\in_array($sortself::SORT_ORDERStrue)) {
  218.                         $errorIo->error(['Wrong sort order''Supported formats are: '.implode(', 'self::SORT_ORDERS).'.']);
  219.                         return 1;
  220.                     }
  221.                     if (self::DESC === $sort) {
  222.                         rsort($list);
  223.                     } else {
  224.                         sort($list);
  225.                     }
  226.                 }
  227.                 $io->section(sprintf('Messages extracted for domain "<info>%s</info>" (%d message%s)'$domain$domainMessagesCount$domainMessagesCount 's' ''));
  228.                 $io->listing($list);
  229.                 $extractedMessagesCount += $domainMessagesCount;
  230.             }
  231.             if ('xlf' === $format) {
  232.                 $io->comment(sprintf('Xliff output version is <info>%s</info>'$xliffVersion));
  233.             }
  234.             $resultMessage sprintf('%d message%s successfully extracted'$extractedMessagesCount$extractedMessagesCount 's were' ' was');
  235.         }
  236.         // save the files
  237.         if (true === $input->getOption('force')) {
  238.             $io->comment('Writing files...');
  239.             $bundleTransPath false;
  240.             foreach ($transPaths as $path) {
  241.                 if (is_dir($path)) {
  242.                     $bundleTransPath $path;
  243.                 }
  244.             }
  245.             if (!$bundleTransPath) {
  246.                 $bundleTransPath end($transPaths);
  247.             }
  248.             $this->writer->write($operation->getResult(), $format, ['path' => $bundleTransPath'default_locale' => $this->defaultLocale'xliff_version' => $xliffVersion'as_tree' => $input->getOption('as-tree'), 'inline' => $input->getOption('as-tree') ?? 0]);
  249.             if (true === $input->getOption('dump-messages')) {
  250.                 $resultMessage .= ' and translation files were updated';
  251.             }
  252.         }
  253.         $io->success($resultMessage.'.');
  254.         return 0;
  255.     }
  256.     public function complete(CompletionInput $inputCompletionSuggestions $suggestions): void
  257.     {
  258.         if ($input->mustSuggestArgumentValuesFor('locale')) {
  259.             $suggestions->suggestValues($this->enabledLocales);
  260.             return;
  261.         }
  262.         /** @var KernelInterface $kernel */
  263.         $kernel $this->getApplication()->getKernel();
  264.         if ($input->mustSuggestArgumentValuesFor('bundle')) {
  265.             $bundles = [];
  266.             foreach ($kernel->getBundles() as $bundle) {
  267.                 $bundles[] = $bundle->getName();
  268.                 if ($bundle->getContainerExtension()) {
  269.                     $bundles[] = $bundle->getContainerExtension()->getAlias();
  270.                 }
  271.             }
  272.             $suggestions->suggestValues($bundles);
  273.             return;
  274.         }
  275.         if ($input->mustSuggestOptionValuesFor('format')) {
  276.             $suggestions->suggestValues(array_merge(
  277.                 $this->writer->getFormats(),
  278.                 array_keys(self::FORMATS)
  279.             ));
  280.             return;
  281.         }
  282.         if ($input->mustSuggestOptionValuesFor('domain') && $locale $input->getArgument('locale')) {
  283.             $extractedCatalogue $this->extractMessages($locale$this->getRootCodePaths($kernel), $input->getOption('prefix'));
  284.             $currentCatalogue $this->loadCurrentMessages($locale$this->getRootTransPaths());
  285.             // process catalogues
  286.             $operation $input->getOption('clean')
  287.                 ? new TargetOperation($currentCatalogue$extractedCatalogue)
  288.                 : new MergeOperation($currentCatalogue$extractedCatalogue);
  289.             $suggestions->suggestValues($operation->getDomains());
  290.             return;
  291.         }
  292.         if ($input->mustSuggestOptionValuesFor('sort')) {
  293.             $suggestions->suggestValues(self::SORT_ORDERS);
  294.         }
  295.     }
  296.     private function filterCatalogue(MessageCatalogue $cataloguestring $domain): MessageCatalogue
  297.     {
  298.         $filteredCatalogue = new MessageCatalogue($catalogue->getLocale());
  299.         // extract intl-icu messages only
  300.         $intlDomain $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX;
  301.         if ($intlMessages $catalogue->all($intlDomain)) {
  302.             $filteredCatalogue->add($intlMessages$intlDomain);
  303.         }
  304.         // extract all messages and subtract intl-icu messages
  305.         if ($messages array_diff($catalogue->all($domain), $intlMessages)) {
  306.             $filteredCatalogue->add($messages$domain);
  307.         }
  308.         foreach ($catalogue->getResources() as $resource) {
  309.             $filteredCatalogue->addResource($resource);
  310.         }
  311.         if ($metadata $catalogue->getMetadata(''$intlDomain)) {
  312.             foreach ($metadata as $k => $v) {
  313.                 $filteredCatalogue->setMetadata($k$v$intlDomain);
  314.             }
  315.         }
  316.         if ($metadata $catalogue->getMetadata(''$domain)) {
  317.             foreach ($metadata as $k => $v) {
  318.                 $filteredCatalogue->setMetadata($k$v$domain);
  319.             }
  320.         }
  321.         return $filteredCatalogue;
  322.     }
  323.     private function extractMessages(string $locale, array $transPathsstring $prefix): MessageCatalogue
  324.     {
  325.         $extractedCatalogue = new MessageCatalogue($locale);
  326.         $this->extractor->setPrefix($prefix);
  327.         foreach ($transPaths as $path) {
  328.             if (is_dir($path) || is_file($path)) {
  329.                 $this->extractor->extract($path$extractedCatalogue);
  330.             }
  331.         }
  332.         return $extractedCatalogue;
  333.     }
  334.     private function loadCurrentMessages(string $locale, array $transPaths): MessageCatalogue
  335.     {
  336.         $currentCatalogue = new MessageCatalogue($locale);
  337.         foreach ($transPaths as $path) {
  338.             if (is_dir($path)) {
  339.                 $this->reader->read($path$currentCatalogue);
  340.             }
  341.         }
  342.         return $currentCatalogue;
  343.     }
  344.     private function getRootTransPaths(): array
  345.     {
  346.         $transPaths $this->transPaths;
  347.         if ($this->defaultTransPath) {
  348.             $transPaths[] = $this->defaultTransPath;
  349.         }
  350.         return $transPaths;
  351.     }
  352.     private function getRootCodePaths(KernelInterface $kernel): array
  353.     {
  354.         $codePaths $this->codePaths;
  355.         $codePaths[] = $kernel->getProjectDir().'/src';
  356.         if ($this->defaultViewsPath) {
  357.             $codePaths[] = $this->defaultViewsPath;
  358.         }
  359.         return $codePaths;
  360.     }
  361. }