Passed
Pull Request — master (#2045)
by Arnaud
06:45
created

UtilTranslationsExtract::loadCurrentMessages()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Command;
15
16
use Cecil\Exception\RuntimeException;
17
use Symfony\Bridge\Twig\Translation\TwigExtractor;
18
use Symfony\Component\Console\Input\InputArgument;
19
use Symfony\Component\Console\Input\InputInterface;
20
use Symfony\Component\Console\Input\InputOption;
21
use Symfony\Component\Console\Output\OutputInterface;
22
use Symfony\Component\Translation\Catalogue\OperationInterface;
23
use Symfony\Component\Translation\Catalogue\MergeOperation;
24
use Symfony\Component\Translation\Catalogue\TargetOperation;
25
use Symfony\Component\Translation\Dumper\PoFileDumper;
26
use Symfony\Component\Translation\Dumper\YamlFileDumper;
27
use Symfony\Component\Translation\MessageCatalogue;
28
use Symfony\Component\Translation\MessageCatalogueInterface;
29
use Symfony\Component\Translation\Reader\TranslationReader;
30
use Symfony\Component\Translation\Writer\TranslationWriter;
31
use Symfony\Component\Translation\Loader\PoFileLoader;
32
use Symfony\Component\Translation\Loader\YamlFileLoader;
33
34
class UtilTranslationsExtract extends AbstractCommand
35
{
36
    private TranslationWriter $writer;
37
    private TranslationReader $reader;
38
    private TwigExtractor $extractor;
39
40
    protected function configure(): void
41
    {
42
        $this
43
            ->setName('util:translations:extract')
44
            ->setDescription('Extracts translations from layouts')
45
            ->setDefinition([
46
                new InputArgument('path', InputArgument::OPTIONAL, 'Use the given path as working directory'),
47
                new InputOption('locale', null, InputOption::VALUE_OPTIONAL, 'The locale', 'fr'),
48
                new InputOption('show', null, InputOption::VALUE_NONE, 'Should the messages be displayed in the console'),
49
                new InputOption('save', null, InputOption::VALUE_NONE, 'Should the extract be done'),
50
                new InputOption('format', null, InputOption::VALUE_OPTIONAL, 'Override the default output format', 'po'),
51
                new InputOption('theme', null, InputOption::VALUE_OPTIONAL, 'Use if you want to translate a theme layouts too'),
52
            ])
53
            ->setHelp(
54
                <<<'EOF'
55
The <info>%command.name%</info> command extracts translation strings from your layouts.
56
It can display them or merge the new ones into the translation file.
57
When new translation strings are found it automatically add a <info>NEW_</info> prefix to the translation message.
58
59
Example running against working directory:
60
61
  <info>php %command.full_name% --show</info>
62
  <info>php %command.full_name% --save --locale=en</info>
63
64
You can extract, and merge, translations from a given theme with <comment>--theme</> option:
65
66
  <info>php %command.full_name% --show --theme=hyde</info>
67
EOF
68
            )
69
        ;
70
    }
71
72
    protected function execute(InputInterface $input, OutputInterface $output): int
73
    {
74
        $config = $this->getBuilder()->getConfig();
75
        $layoutsPath = $config->getLayoutsPath();
76
        $translationsPath = $config->getTranslationsPath();
77
78
        $this->initializeTranslationComponents();
79
80
        $this->checkOptions($input);
81
82
        if ($input->getOption('theme')) {
83
            $layoutsPath = [$layoutsPath, $config->getThemeDirPath($input->getOption('theme'))];
84
        }
85
86
        $this->initializeTwigExtractor($layoutsPath);
87
88
        $output->writeln(\sprintf('Generating "<info>%s</info>" translation file', $input->getOption('locale')));
89
90
        $output->writeln('Parsing templates...');
91
        $extractedCatalogue = $this->extractMessages($input->getOption('locale'), $layoutsPath, 'NEW_');
92
93
        $output->writeln('Loading translation file...');
94
        $currentCatalogue = $this->loadCurrentMessages($input->getOption('locale'), $translationsPath);
95
96
        try {
97
            $operation = $input->getOption('theme')
98
                ? new MergeOperation($currentCatalogue, $extractedCatalogue)
99
                : new TargetOperation($currentCatalogue, $extractedCatalogue);
100
        } catch (\Exception $e) {
101
            throw new RuntimeException($e->getMessage());
102
        }
103
104
        // show compiled list of messages
105
        if (true === $input->getOption('show')) {
106
            try {
107
                $this->dumpMessages($operation);
108
            } catch (\Exception $e) {
109
                throw new RuntimeException('Error while displaying messages: ' . $e->getMessage());
110
            }
111
        }
112
113
        // save the file
114
        if (true === $input->getOption('save')) {
115
            try {
116
                $this->saveDump($operation->getResult(), $input->getOption('format'), $translationsPath);
117
            } catch (\InvalidArgumentException $e) {
118
                throw new RuntimeException('Error while saving translation file: ' . $e->getMessage());
119
            }
120
        }
121
122
        return 0;
123
    }
124
125
    private function checkOptions(InputInterface $input): void
126
    {
127
        if (true !== $input->getOption('save') && true !== $input->getOption('show')) {
128
            throw new RuntimeException('You must choose to display (`--show`) and/or save (`--save`) the translations');
129
        }
130
        if (!\in_array($input->getOption('format'), $this->writer->getFormats(), true)) {
131
            throw new RuntimeException(\sprintf('Supported formats are: %s', implode(', ', $this->writer->getFormats())));
132
        }
133
    }
134
135
    private function initializeTranslationComponents(): void
136
    {
137
        $this->reader = new TranslationReader();
138
        $this->reader->addLoader('po', new PoFileLoader());
139
        $this->reader->addLoader('yaml', new YamlFileLoader());
140
        $this->writer = new TranslationWriter();
141
        $this->writer->addDumper('po', new PoFileDumper());
142
        $this->writer->addDumper('yaml', new YamlFileDumper());
143
    }
144
145
    private function initializeTwigExtractor($layoutsPath = []): void
146
    {
147
        $twig = (new \Cecil\Renderer\Twig($this->getBuilder(), $layoutsPath))->getTwig();
148
        $this->extractor = new TwigExtractor($twig);
149
    }
150
151
    private function extractMessages(string $locale, $layoutsPath, string $prefix): MessageCatalogue
152
    {
153
        $extractedCatalogue = new MessageCatalogue($locale);
154
        $this->extractor->setPrefix($prefix);
155
        $layoutsPath = \is_array($layoutsPath) ? $layoutsPath : [$layoutsPath];
156
        foreach ($layoutsPath as $path) {
157
            $this->extractor->extract($path, $extractedCatalogue);
158
        }
159
160
        return $extractedCatalogue;
161
    }
162
163
    private function loadCurrentMessages(string $locale, string $translationsPath): MessageCatalogue
164
    {
165
        $currentCatalogue = new MessageCatalogue($locale);
166
        if (is_dir($translationsPath)) {
167
            $this->reader->read($translationsPath, $currentCatalogue);
168
        }
169
170
        return $currentCatalogue;
171
    }
172
173
    private function saveDump(MessageCatalogueInterface $messageCatalogue, string $format, string $translationsPath): void
174
    {
175
        $this->io->writeln('Writing file...');
176
        $this->writer->write($messageCatalogue, $format, ['path' => $translationsPath]);
177
        $this->io->success('Translation file have been successfully updated.');
178
    }
179
180
    private function dumpMessages(OperationInterface $operation): void
181
    {
182
        $messagesCount = 0;
183
        $this->io->newLine();
184
        foreach ($operation->getDomains() as $domain) {
185
            $newKeys = array_keys($operation->getNewMessages($domain));
186
            $allKeys = array_keys($operation->getMessages($domain));
187
            $list = array_merge(
188
                array_diff($allKeys, $newKeys),
189
                array_map(fn ($key) => \sprintf('<fg=green>%s</>', $key), $newKeys),
190
                array_map(
191
                    fn ($key) => \sprintf('<fg=red>%s</>', $key),
192
                    array_keys($operation->getObsoleteMessages($domain))
193
                )
194
            );
195
            $domainMessagesCount = \count($list);
196
            sort($list);
197
            $this->io->listing($list);
198
            $messagesCount += $domainMessagesCount;
199
        }
200
201
        $this->io->success(
202
            \sprintf(
203
                '%d message%s successfully extracted.',
204
                $messagesCount,
205
                $messagesCount > 1 ? 's were' : ' was'
206
            )
207
        );
208
    }
209
}
210