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

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