-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathImportTranslationsCommand.php
More file actions
325 lines (267 loc) · 12.6 KB
/
ImportTranslationsCommand.php
File metadata and controls
325 lines (267 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
<?php
namespace Lexik\Bundle\TranslationBundle\Command;
use Lexik\Bundle\TranslationBundle\Manager\LocaleManagerInterface;
use Lexik\Bundle\TranslationBundle\Translation\Importer\FileImporter;
use LogicException;
use ReflectionClass;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Validator\Validation;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Imports translation files content in the database.
* Only imports files for locales defined in lexik_translation.managed_locales.
*
* @author Cédric Girard <c.girard@lexik.fr>
* @author Nikola Petkanski <nikola@petkanski.com>
*/
#[AsCommand(
name: 'lexik:translations:import',
description: 'Import all translations from flat files (xliff, yml, php) into the database.',
help: <<<'HELP'
The <info>%command.name%</info> command imports translation files from your project into the database.
By default, the command imports translations from:
- Application translation files (<comment>translations/</comment> directory)
- Bundle translation files
- Component translation files
You can filter the import by locales:
<info>php %command.full_name% --locales=en,fr</info>
You can also import from a specific path:
<info>php %command.full_name% --import-path=/path/to/translations</info>
Use <comment>--force</comment> to replace existing translations in the database.
Use <comment>--merge</comment> to merge translations (keeps the latest updatedAt date).
Use <comment>--cache-clear</comment> to remove translation cache files after import.
HELP
)]
class ImportTranslationsCommand extends Command
{
public function __construct(
private readonly TranslatorInterface $translator,
private readonly LocaleManagerInterface $localeManager,
private readonly FileImporter $fileImporter,
private readonly KernelInterface $kernel,
#[Autowire('%kernel.project_dir%')]
private readonly string $projectDir,
) {
parent::__construct();
}
private ?InputInterface $input = null;
private ?OutputInterface $output = null;
/**
* {@inheritdoc}
*/
protected function configure(): void
{
$this->addOption('cache-clear', 'c', InputOption::VALUE_NONE, 'Remove translations cache files for managed locales.');
$this->addOption('force', 'f', InputOption::VALUE_NONE, 'Force import, replace database content.');
$this->addOption('globals', 'g', InputOption::VALUE_NONE, 'Import only globals (app/Resources/translations.');
$this->addOption('locales', 'l', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Import only for these locales, instead of using the managed locales.');
$this->addOption('domains', 'd', InputOption::VALUE_OPTIONAL, 'Only imports files for given domains (comma separated).');
$this->addOption('case-insensitive', 'i', InputOption::VALUE_NONE, 'Process translation as lower case to avoid duplicate entry errors.');
$this->addOption('merge', 'm', InputOption::VALUE_NONE, 'Merge translation (use ones with latest updatedAt date).');
$this->addOption('import-path', 'p', InputOption::VALUE_REQUIRED, 'Search for translations at given path');
$this->addOption('only-vendors', 'o', InputOption::VALUE_NONE, 'Import from vendors only');
$this->addArgument('bundle', InputArgument::OPTIONAL, 'Import translations for this specific bundle.', null);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->input = $input;
$this->output = $output;
$this->checkOptions();
$locales = $this->input->getOption('locales');
if (empty($locales)) {
$locales = $this->localeManager->getLocales();
}
$domains = $input->getOption('domains') ? explode(',', (string)$input->getOption('domains')) : [];
$bundleName = $this->input->getArgument('bundle');
if ($bundleName) {
$bundle = $this->kernel->getBundle($bundleName);
$this->importBundleTranslationFiles($bundle, $locales, $domains, (bool)$this->input->getOption('globals'));
} else {
if (!$this->input->getOption('import-path')) {
if (!$this->input->getOption('merge') && !$this->input->getOption('only-vendors')) {
$this->output->writeln('<info>*** Importing application translation files ***</info>');
$this->importAppTranslationFiles($locales, $domains);
}
if ($this->input->getOption('globals')) {
$this->importBundlesTranslationFiles($locales, $domains, true);
}
if (!$this->input->getOption('globals')) {
$this->output->writeln('<info>*** Importing bundles translation files ***</info>');
$this->importBundlesTranslationFiles($locales, $domains);
$this->output->writeln('<info>*** Importing component translation files ***</info>');
$this->importComponentTranslationFiles($locales, $domains);
}
if ($this->input->getOption('merge')) {
$this->output->writeln('<info>*** Importing application translation files ***</info>');
$this->importAppTranslationFiles($locales, $domains);
}
}
}
$importPath = $this->input->getOption('import-path');
if (!empty($importPath)) {
$this->output->writeln(sprintf('<info>*** Importing translations from path "%s" ***</info>', $importPath));
$this->importTranslationFilesFromPath($importPath, $locales, $domains);
}
if ($this->input->getOption('cache-clear') && method_exists($this->translator, 'removeLocalesCacheFiles')) {
$this->output->writeln('<info>Removing translations cache files ...</info>');
$this->translator->removeLocalesCacheFiles($locales);
}
return 0;
}
/**
* Checks if given options are compatible.
*/
protected function checkOptions()
{
if ($this->input->getOption('only-vendors') && $this->input->getOption('globals')) {
throw new LogicException('You cannot use "globals" and "only-vendors" at the same time.');
}
if ($this->input->getOption('import-path')
&& ($this->input->getOption('globals')
|| $this->input->getOption('merge')
|| $this->input->getOption('only-vendors'))) {
throw new LogicException('You cannot use "globals", "merge" or "only-vendors" and "import-path" at the same time.');
}
}
/**
* @param string $path
*/
protected function importTranslationFilesFromPath($path, array $locales, array $domains)
{
$finder = $this->findTranslationsFiles($path, $locales, $domains, false);
$this->importTranslationFiles($finder);
}
/**
* Imports Symfony's components translation files.
*/
protected function importComponentTranslationFiles(array $locales, array $domains)
{
$classes = [
Validation::class => '/Resources/translations',
Form::class => '/Resources/translations',
AuthenticationException::class => '/../Resources/translations',
];
$dirs = [];
foreach ($classes as $namespace => $translationDir) {
$reflection = new ReflectionClass($namespace);
$dirs[] = dirname($reflection->getFilename()) . $translationDir;
}
$finder = new Finder();
$finder->files()
->name($this->getFileNamePattern($locales, $domains))
->in($dirs);
$this->importTranslationFiles($finder->count() > 0 ? $finder : null);
}
/**
* Imports application translation files.
*/
protected function importAppTranslationFiles(array $locales, array $domains): void
{
$translationPath = $this->projectDir . '/translations';
$finder = $this->findTranslationsFiles($translationPath, $locales, $domains, false);
$this->importTranslationFiles($finder);
}
/**
* Imports translation files form all bundles.
*
* @param boolean $global
*/
protected function importBundlesTranslationFiles(array $locales, array $domains, $global = false)
{
$bundles = $this->kernel->getBundles();
foreach ($bundles as $bundle) {
$this->importBundleTranslationFiles($bundle, $locales, $domains, $global);
}
}
/**
* Imports translation files form the specific bundles.
*/
protected function importBundleTranslationFiles(BundleInterface $bundle, array $locales, array $domains, bool $global = false): void
{
if ($global) {
$path = $this->projectDir . '/app';
$path .= '/Resources/' . $bundle->getName() . '/translations';
$this->output->writeln('<info>*** Importing ' . $bundle->getName() . '`s translation files from ' . $path . ' ***</info>');
$this->output->writeln(sprintf('<info># %s:</info>', $bundle->getName()));
$finder = $this->findTranslationsFiles($path, $locales, $domains);
$this->importTranslationFiles($finder);
return;
}
$paths = [
$bundle->getPath() . '/translations',
$bundle->getPath() . '/Resources/translations',
];
foreach ($paths as $path) {
$this->output->writeln(sprintf('<info># %s:</info>', $bundle->getName()));
$finder = $this->findTranslationsFiles($path, $locales, $domains, false);
$this->importTranslationFiles($finder);
}
}
/**
* Imports some translations files.
*/
protected function importTranslationFiles(?Finder $finder): void
{
if (!$finder instanceof Finder) {
$this->output->writeln('No file to import');
return;
}
$this->fileImporter->setCaseInsensitiveInsert($this->input->getOption('case-insensitive'));
foreach ($finder as $file) {
$this->output->write(sprintf('Importing <comment>"%s"</comment> ... ', $file->getPathname()));
$number = $this->fileImporter->import($file, $this->input->getOption('force'), $this->input->getOption('merge'));
$this->output->writeln(sprintf('%d translations', $number));
$skipped = $this->fileImporter->getSkippedKeys();
if (count($skipped) > 0) {
$this->output->writeln(sprintf(' <error>[!]</error> The following keys has been skipped: "%s".', implode('", "', $skipped)));
}
}
}
/**
* Return a Finder object if $path has a Resources/translations folder.
*/
protected function findTranslationsFiles(string $path, array $locales, array $domains, $autocompletePath = true): ?Finder
{
$finder = null;
if (0 === stripos(PHP_OS_FAMILY, "win")) {
$path = preg_replace('#' . preg_quote(DIRECTORY_SEPARATOR, '#') . '#', '/', $path);
}
if (true === $autocompletePath) {
$dir = (str_starts_with((string) $path, $this->projectDir . '/Resources')) ? $path : $path . '/Resources/translations';
} else {
$dir = $path;
}
$this->output->writeln('<info>*** Using dir ' . $dir . ' to lookup translation files. ***</info>');
if (is_dir($dir)) {
$finder = new Finder();
$finder->files()
->name($this->getFileNamePattern($locales, $domains))
->in($dir);
}
return (null !== $finder && $finder->count() > 0) ? $finder : null;
}
protected function getFileNamePattern(array $locales, array $domains): string
{
$formats = method_exists($this->translator, 'getFormats') ? $this->translator->getFormats() : [];
if (count($domains)) {
$regex = sprintf('/((%s)\.(%s)\.(%s))/', implode('|', $domains), implode('|', $locales), implode('|', $formats));
} else {
$regex = sprintf('/(.*\.(%s)\.(%s))/', implode('|', $locales), implode('|', $formats));
}
return $regex;
}
}