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

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