Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
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(function ($translation) {
91
        return count($translation['missingKeys']);
92
    }, array_values($translationStatus)));
93
    $totalTranslationMismatches += array_sum(array_map(function ($translation) {
94
        return count($translation['mismatches']);
95
    }, array_values($translationStatus)));
96
 
97
    printTranslationStatus($originalFilePath, $translationStatus, $config['verbose_output'], $config['include_completed_languages']);
98
}
99
 
100
exit($totalTranslationMismatches > 0 ? 1 : 0);
101
 
102
function findTranslationFiles($originalFilePath, $localeToAnalyze)
103
{
104
    $translations = [];
105
 
106
    $translationsDir = dirname($originalFilePath);
107
    $originalFileName = basename($originalFilePath);
108
    $translationFileNamePattern = str_replace('.en.', '.*.', $originalFileName);
109
 
110
    $translationFiles = glob($translationsDir.'/'.$translationFileNamePattern, \GLOB_NOSORT);
111
    sort($translationFiles);
112
    foreach ($translationFiles as $filePath) {
113
        $locale = extractLocaleFromFilePath($filePath);
114
 
115
        if (null !== $localeToAnalyze && $locale !== $localeToAnalyze) {
116
            continue;
117
        }
118
 
119
        $translations[$locale] = $filePath;
120
    }
121
 
122
    return $translations;
123
}
124
 
125
function calculateTranslationStatus($originalFilePath, $translationFilePaths)
126
{
127
    $translationStatus = [];
128
    $allTranslationKeys = extractTranslationKeys($originalFilePath);
129
 
130
    foreach ($translationFilePaths as $locale => $translationPath) {
131
        $translatedKeys = extractTranslationKeys($translationPath);
132
        $missingKeys = array_diff_key($allTranslationKeys, $translatedKeys);
133
        $mismatches = findTransUnitMismatches($allTranslationKeys, $translatedKeys);
134
 
135
        $translationStatus[$locale] = [
136
            'total' => count($allTranslationKeys),
137
            'translated' => count($translatedKeys),
138
            'missingKeys' => $missingKeys,
139
            'mismatches' => $mismatches,
140
        ];
141
        $translationStatus[$locale]['is_completed'] = isTranslationCompleted($translationStatus[$locale]);
142
    }
143
 
144
    return $translationStatus;
145
}
146
 
147
function isTranslationCompleted(array $translationStatus): bool
148
{
149
    return $translationStatus['total'] === $translationStatus['translated'] && 0 === count($translationStatus['mismatches']);
150
}
151
 
152
function printTranslationStatus($originalFilePath, $translationStatus, $verboseOutput, $includeCompletedLanguages)
153
{
154
    printTitle($originalFilePath);
155
    printTable($translationStatus, $verboseOutput, $includeCompletedLanguages);
156
    echo \PHP_EOL.\PHP_EOL;
157
}
158
 
159
function extractLocaleFromFilePath($filePath)
160
{
161
    $parts = explode('.', $filePath);
162
 
163
    return $parts[count($parts) - 2];
164
}
165
 
166
function extractTranslationKeys($filePath)
167
{
168
    $translationKeys = [];
169
    $contents = new \SimpleXMLElement(file_get_contents($filePath));
170
 
171
    foreach ($contents->file->body->{'trans-unit'} as $translationKey) {
172
        $translationId = (string) $translationKey['id'];
173
        $translationKey = (string) $translationKey->source;
174
 
175
        $translationKeys[$translationId] = $translationKey;
176
    }
177
 
178
    return $translationKeys;
179
}
180
 
181
/**
182
 * Check whether the trans-unit id and source match with the base translation.
183
 */
184
function findTransUnitMismatches(array $baseTranslationKeys, array $translatedKeys): array
185
{
186
    $mismatches = [];
187
 
188
    foreach ($baseTranslationKeys as $translationId => $translationKey) {
189
        if (!isset($translatedKeys[$translationId])) {
190
            continue;
191
        }
192
        if ($translatedKeys[$translationId] !== $translationKey) {
193
            $mismatches[$translationId] = [
194
                'found' => $translatedKeys[$translationId],
195
                'expected' => $translationKey,
196
            ];
197
        }
198
    }
199
 
200
    return $mismatches;
201
}
202
 
203
function printTitle($title)
204
{
205
    echo $title.\PHP_EOL;
206
    echo str_repeat('=', strlen($title)).\PHP_EOL.\PHP_EOL;
207
}
208
 
209
function printTable($translations, $verboseOutput, bool $includeCompletedLanguages)
210
{
211
    if (0 === count($translations)) {
212
        echo 'No translations found';
213
 
214
        return;
215
    }
216
    $longestLocaleNameLength = max(array_map('strlen', array_keys($translations)));
217
 
218
    foreach ($translations as $locale => $translation) {
219
        if (!$includeCompletedLanguages && $translation['is_completed']) {
220
            continue;
221
        }
222
 
223
        if ($translation['translated'] > $translation['total']) {
224
            textColorRed();
225
        } elseif (count($translation['mismatches']) > 0) {
226
            textColorRed();
227
        } elseif ($translation['is_completed']) {
228
            textColorGreen();
229
        }
230
 
231
        echo sprintf(
232
            '|  Locale: %-'.$longestLocaleNameLength.'s  |  Translated: %2d/%2d  |  Mismatches: %d  |',
233
            $locale,
234
            $translation['translated'],
235
            $translation['total'],
236
            count($translation['mismatches'])
237
        ).\PHP_EOL;
238
 
239
        textColorNormal();
240
 
241
        $shouldBeClosed = false;
242
        if (true === $verboseOutput && count($translation['missingKeys']) > 0) {
243
            echo '|    Missing Translations:'.\PHP_EOL;
244
 
245
            foreach ($translation['missingKeys'] as $id => $content) {
246
                echo sprintf('|      (id=%s) %s', $id, $content).\PHP_EOL;
247
            }
248
            $shouldBeClosed = true;
249
        }
250
        if (true === $verboseOutput && count($translation['mismatches']) > 0) {
251
            echo '|    Mismatches between trans-unit id and source:'.\PHP_EOL;
252
 
253
            foreach ($translation['mismatches'] as $id => $content) {
254
                echo sprintf('|      (id=%s) Expected: %s', $id, $content['expected']).\PHP_EOL;
255
                echo sprintf('|              Found:    %s', $content['found']).\PHP_EOL;
256
            }
257
            $shouldBeClosed = true;
258
        }
259
        if ($shouldBeClosed) {
260
            echo str_repeat('-', 80).\PHP_EOL;
261
        }
262
    }
263
}
264
 
265
function textColorGreen()
266
{
267
    echo "\033[32m";
268
}
269
 
270
function textColorRed()
271
{
272
    echo "\033[31m";
273
}
274
 
275
function textColorNormal()
276
{
277
    echo "\033[0m";
278
}