Debian Codegraph @

lib/3rdParty/composer/symfony/translation/Resources/bin/translation-status.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 if ('cli' !== \PHP_SAPI) {
13 throw new Exception('This script must be run from the command line.');
14 }
15
16 $usageInstructions = <<<END
17
18 Usage instructions
19 -------------------------------------------------------------------------------
20
21 $ cd symfony-code-root-directory/
22
23 # show the translation status of all locales
24 $ php translation-status.php
25
26 # only show the translation status of incomplete or erroneous locales
27 $ php translation-status.php --incomplete
28
29 # show the translation status of all locales, all their missing translations and mismatches between trans-unit id and source
30 $ php translation-status.php -v
31
32 # show the status of a single locale
33 $ php translation-status.php fr
34
35 # show the status of a single locale, missing translations and mismatches between trans-unit id and source
36 $ php translation-status.php fr -v
37
38 END;
39
40 $config = [
41 // if TRUE, the full list of missing translations is displayed
42 'verbose_output' => false,
43 // NULL = analyze all locales
44 'locale_to_analyze' => null,
45 // append --incomplete to only show incomplete languages
46 'include_completed_languages' => true,
47 // the reference files all the other translations are compared to
48 'original_files' => [
49 'src/Symfony/Component/Form/Resources/translations/validators.en.xlf',
50 'src/Symfony/Component/Security/Core/Resources/translations/security.en.xlf',
51 'src/Symfony/Component/Validator/Resources/translations/validators.en.xlf',
52 ],
53 ];
54
55 $argc = $_SERVER['argc'];
56 $argv = $_SERVER['argv'];
57
58 if ($argc > 4) {
59 echo str_replace('translation-status.php', $argv[0], $usageInstructions);
60 exit(1);
61 }
62
63 foreach (array_slice($argv, 1) as $argumentOrOption) {
64 if ('--incomplete' === $argumentOrOption) {
65 $config['include_completed_languages'] = false;
66 continue;
67 }
68
69 if (str_starts_with($argumentOrOption, '-')) {
70 $config['verbose_output'] = true;
71 } else {
72 $config['locale_to_analyze'] = $argumentOrOption;
73 }
74 }
75
76 foreach ($config['original_files'] as $originalFilePath) {
77 if (!file_exists($originalFilePath)) {
78 echo sprintf('The following file does not exist. Make sure that you execute this command at the root dir of the Symfony code repository.%s %s', \PHP_EOL, $originalFilePath);
79 exit(1);
80 }
81 }
82
83 $totalMissingTranslations = 0;
84 $totalTranslationMismatches = 0;
85
86 foreach ($config['original_files'] as $originalFilePath) {
87 $translationFilePaths = findTranslationFiles($originalFilePath, $config['locale_to_analyze']);
88 $translationStatus = calculateTranslationStatus($originalFilePath, $translationFilePaths);
89
90 $totalMissingTranslations += array_sum(array_map(static fn ($translation) => count($translation['missingKeys']), array_values($translationStatus)));
91 $totalTranslationMismatches += array_sum(array_map(static fn ($translation) => count($translation['mismatches']), array_values($translationStatus)));
92
93 printTranslationStatus($originalFilePath, $translationStatus, $config['verbose_output'], $config['include_completed_languages']);
94 }
95
96 exit($totalTranslationMismatches > 0 ? 1 : 0);
97
98 function findTranslationFiles($originalFilePath, $localeToAnalyze): array
99 {
100 $translations = [];
101
102 $translationsDir = dirname($originalFilePath);
103 $originalFileName = basename($originalFilePath);
104 $translationFileNamePattern = str_replace('.en.', '.*.', $originalFileName);
105
106 $translationFiles = glob($translationsDir.'/'.$translationFileNamePattern, \GLOB_NOSORT);
107 sort($translationFiles);
108 foreach ($translationFiles as $filePath) {
109 $locale = extractLocaleFromFilePath($filePath);
110
111 if (null !== $localeToAnalyze && $locale !== $localeToAnalyze) {
112 continue;
113 }
114
115 $translations[$locale] = $filePath;
116 }
117
118 return $translations;
119 }
120
121 function calculateTranslationStatus($originalFilePath, $translationFilePaths): array
122 {
123 $translationStatus = [];
124 $allTranslationKeys = extractTranslationKeys($originalFilePath);
125
126 foreach ($translationFilePaths as $locale => $translationPath) {
127 $translatedKeys = extractTranslationKeys($translationPath);
128 $missingKeys = array_diff_key($allTranslationKeys, $translatedKeys);
129 $mismatches = findTransUnitMismatches($allTranslationKeys, $translatedKeys);
130
131 $translationStatus[$locale] = [
132 'total' => count($allTranslationKeys),
133 'translated' => count($translatedKeys),
134 'missingKeys' => $missingKeys,
135 'mismatches' => $mismatches,
136 ];
137 $translationStatus[$locale]['is_completed'] = isTranslationCompleted($translationStatus[$locale]);
138 }
139
140 return $translationStatus;
141 }
142
143 function isTranslationCompleted(array $translationStatus): bool
144 {
145 return $translationStatus['total'] === $translationStatus['translated'] && 0 === count($translationStatus['mismatches']);
146 }
147
148 function printTranslationStatus($originalFilePath, $translationStatus, $verboseOutput, $includeCompletedLanguages)
149 {
150 printTitle($originalFilePath);
151 printTable($translationStatus, $verboseOutput, $includeCompletedLanguages);
152 echo \PHP_EOL.\PHP_EOL;
153 }
154
155 function extractLocaleFromFilePath($filePath)
156 {
157 $parts = explode('.', $filePath);
158
159 return $parts[count($parts) - 2];
160 }
161
162 function extractTranslationKeys($filePath): array
163 {
164 $translationKeys = [];
165 $contents = new SimpleXMLElement(file_get_contents($filePath));
166
167 foreach ($contents->file->body->{'trans-unit'} as $translationKey) {
168 $translationId = (string) $translationKey['id'];
169 $translationKey = (string) ($translationKey['resname'] ?? $translationKey->source);
170
171 $translationKeys[$translationId] = $translationKey;
172 }
173
174 return $translationKeys;
175 }
176
177 /**
178 * Check whether the trans-unit id and source match with the base translation.
179 */
180 function findTransUnitMismatches(array $baseTranslationKeys, array $translatedKeys): array
181 {
182 $mismatches = [];
183
184 foreach ($baseTranslationKeys as $translationId => $translationKey) {
185 if (!isset($translatedKeys[$translationId])) {
186 continue;
187 }
188 if ($translatedKeys[$translationId] !== $translationKey) {
189 $mismatches[$translationId] = [
190 'found' => $translatedKeys[$translationId],
191 'expected' => $translationKey,
192 ];
193 }
194 }
195
196 return $mismatches;
197 }
198
199 function printTitle($title)
200 {
201 echo $title.\PHP_EOL;
202 echo str_repeat('=', strlen($title)).\PHP_EOL.\PHP_EOL;
203 }
204
205 function printTable($translations, $verboseOutput, bool $includeCompletedLanguages)
206 {
207 if (0 === count($translations)) {
208 echo 'No translations found';
209
210 return;
211 }
212 $longestLocaleNameLength = max(array_map('strlen', array_keys($translations)));
213
214 foreach ($translations as $locale => $translation) {
215 if (!$includeCompletedLanguages && $translation['is_completed']) {
216 continue;
217 }
218
219 if ($translation['translated'] > $translation['total']) {
220 textColorRed();
221 } elseif (count($translation['mismatches']) > 0) {
222 textColorRed();
223 } elseif ($translation['is_completed']) {
224 textColorGreen();
225 }
226
227 echo sprintf(
228 '| Locale: %-'.$longestLocaleNameLength.'s | Translated: %2d/%2d | Mismatches: %d |',
229 $locale,
230 $translation['translated'],
231 $translation['total'],
232 count($translation['mismatches'])
233 ).\PHP_EOL;
234
235 textColorNormal();
236
237 $shouldBeClosed = false;
238 if (true === $verboseOutput && count($translation['missingKeys']) > 0) {
239 echo '| Missing Translations:'.\PHP_EOL;
240
241 foreach ($translation['missingKeys'] as $id => $content) {
242 echo sprintf('| (id=%s) %s', $id, $content).\PHP_EOL;
243 }
244 $shouldBeClosed = true;
245 }
246 if (true === $verboseOutput && count($translation['mismatches']) > 0) {
247 echo '| Mismatches between trans-unit id and source:'.\PHP_EOL;
248
249 foreach ($translation['mismatches'] as $id => $content) {
250 echo sprintf('| (id=%s) Expected: %s', $id, $content['expected']).\PHP_EOL;
251 echo sprintf('| Found: %s', $content['found']).\PHP_EOL;
252 }
253 $shouldBeClosed = true;
254 }
255 if ($shouldBeClosed) {
256 echo str_repeat('-', 80).\PHP_EOL;
257 }
258 }
259 }
260
261 function textColorGreen()
262 {
263 echo "\033[32m";
264 }
265
266 function textColorRed()
267 {
268 echo "\033[31m";
269 }
270
271 function textColorNormal()
272 {
273 echo "\033[0m";
274 }