| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Translation\Command; |
| 13 |
|
| 14 |
use Symfony\Component\Console\Attribute\AsCommand; |
| 15 |
use Symfony\Component\Console\CI\GithubActionReporter; |
| 16 |
use Symfony\Component\Console\Command\Command; |
| 17 |
use Symfony\Component\Console\Completion\CompletionInput; |
| 18 |
use Symfony\Component\Console\Completion\CompletionSuggestions; |
| 19 |
use Symfony\Component\Console\Exception\RuntimeException; |
| 20 |
use Symfony\Component\Console\Input\InputArgument; |
| 21 |
use Symfony\Component\Console\Input\InputInterface; |
| 22 |
use Symfony\Component\Console\Input\InputOption; |
| 23 |
use Symfony\Component\Console\Output\OutputInterface; |
| 24 |
use Symfony\Component\Console\Style\SymfonyStyle; |
| 25 |
use Symfony\Component\Translation\Exception\InvalidArgumentException; |
| 26 |
use Symfony\Component\Translation\Util\XliffUtils; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
> |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
#[AsCommand(name: 'lint:xliff', description: 'Lint an XLIFF file and outputs encountered errors')] |
| 36 |
class XliffLintCommand extends Command |
| 37 |
{ |
| 38 |
private string $format; |
| 39 |
private bool $displayCorrectFiles; |
| 40 |
private ?\Closure $directoryIteratorProvider; |
| 41 |
private ?\Closure $isReadableProvider; |
| 42 |
|
| 43 |
public function __construct( |
| 44 |
?string $name = null, |
| 45 |
?callable $directoryIteratorProvider = null, |
| 46 |
?callable $isReadableProvider = null, |
| 47 |
private bool $requireStrictFileNames = true, |
| 48 |
) { |
| 49 |
parent::__construct($name); |
| 50 |
|
| 51 |
$this->directoryIteratorProvider = null === $directoryIteratorProvider ? null : $directoryIteratorProvider(...); |
| 52 |
$this->isReadableProvider = null === $isReadableProvider ? null : $isReadableProvider(...); |
| 53 |
} |
| 54 |
|
| 55 |
protected function configure(): void |
| 56 |
{ |
| 57 |
$this |
| 58 |
->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from STDIN') |
| 59 |
->addOption('format', null, InputOption::VALUE_REQUIRED, \sprintf('The output format ("%s")', implode('", "', $this->getAvailableFormatOptions()))) |
| 60 |
->setHelp(<<<EOF |
| 61 |
The <info>%command.name%</info> command lints an XLIFF file and outputs to STDOUT |
| 62 |
the first encountered syntax error. |
| 63 |
|
| 64 |
You can validates XLIFF contents passed from STDIN: |
| 65 |
|
| 66 |
<info>cat filename | php %command.full_name% -</info> |
| 67 |
|
| 68 |
You can also validate the syntax of a file: |
| 69 |
|
| 70 |
<info>php %command.full_name% filename</info> |
| 71 |
|
| 72 |
Or of a whole directory: |
| 73 |
|
| 74 |
<info>php %command.full_name% dirname</info> |
| 75 |
|
| 76 |
The <info>--format</info> option specifies the format of the command output: |
| 77 |
|
| 78 |
<info>php %command.full_name% dirname --format=json</info> |
| 79 |
|
| 80 |
EOF |
| 81 |
) |
| 82 |
; |
| 83 |
} |
| 84 |
|
| 85 |
protected function execute(InputInterface $input, OutputInterface $output): int |
| 86 |
{ |
| 87 |
$io = new SymfonyStyle($input, $output); |
| 88 |
$filenames = (array) $input->getArgument('filename'); |
| 89 |
$this->format = $input->getOption('format') ?? (GithubActionReporter::isGithubActionEnvironment() ? 'github' : 'txt'); |
| 90 |
$this->displayCorrectFiles = $output->isVerbose(); |
| 91 |
|
| 92 |
if (['-'] === $filenames) { |
| 93 |
return $this->display($io, [$this->validate(file_get_contents('php://stdin'))]); |
| 94 |
} |
| 95 |
|
| 96 |
if (!$filenames) { |
| 97 |
throw new RuntimeException('Please provide a filename or pipe file content to STDIN.'); |
| 98 |
} |
| 99 |
|
| 100 |
$filesInfo = []; |
| 101 |
foreach ($filenames as $filename) { |
| 102 |
if (!$this->isReadable($filename)) { |
| 103 |
throw new RuntimeException(\sprintf('File or directory "%s" is not readable.', $filename)); |
| 104 |
} |
| 105 |
|
| 106 |
foreach ($this->getFiles($filename) as $file) { |
| 107 |
$filesInfo[] = $this->validate(file_get_contents($file), $file); |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
return $this->display($io, $filesInfo); |
| 112 |
} |
| 113 |
|
| 114 |
private function validate(string $content, ?string $file = null): array |
| 115 |
{ |
| 116 |
$errors = []; |
| 117 |
|
| 118 |
|
| 119 |
if ('' === trim($content)) { |
| 120 |
return ['file' => $file, 'valid' => true]; |
| 121 |
} |
| 122 |
|
| 123 |
$internal = libxml_use_internal_errors(true); |
| 124 |
|
| 125 |
$document = new \DOMDocument(); |
| 126 |
$document->loadXML($content); |
| 127 |
|
| 128 |
if (null !== $targetLanguage = $this->getTargetLanguageFromFile($document)) { |
| 129 |
$normalizedLocalePattern = \sprintf('(%s|%s)', preg_quote($targetLanguage, '/'), preg_quote(str_replace('-', '_', $targetLanguage), '/')); |
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
$expectedFilenamePattern = $this->requireStrictFileNames ? \sprintf('/^.*\.(?i:%s)\.(?:xlf|xliff)/', $normalizedLocalePattern) : \sprintf('/^(?:.*\.(?i:%s)|(?i:%s)\..*)\.(?:xlf|xliff)/', $normalizedLocalePattern, $normalizedLocalePattern); |
| 135 |
|
| 136 |
if (0 === preg_match($expectedFilenamePattern, basename($file))) { |
| 137 |
$errors[] = [ |
| 138 |
'line' => -1, |
| 139 |
'column' => -1, |
| 140 |
'message' => \sprintf('There is a mismatch between the language included in the file name ("%s") and the "%s" value used in the "target-language" attribute of the file.', basename($file), $targetLanguage), |
| 141 |
]; |
| 142 |
} |
| 143 |
} |
| 144 |
|
| 145 |
foreach (XliffUtils::validateSchema($document) as $xmlError) { |
| 146 |
$errors[] = [ |
| 147 |
'line' => $xmlError['line'], |
| 148 |
'column' => $xmlError['column'], |
| 149 |
'message' => $xmlError['message'], |
| 150 |
]; |
| 151 |
} |
| 152 |
|
| 153 |
libxml_clear_errors(); |
| 154 |
libxml_use_internal_errors($internal); |
| 155 |
|
| 156 |
return ['file' => $file, 'valid' => 0 === \count($errors), 'messages' => $errors]; |
| 157 |
} |
| 158 |
|
| 159 |
private function display(SymfonyStyle $io, array $files): int |
| 160 |
{ |
| 161 |
return match ($this->format) { |
| 162 |
'txt' => $this->displayTxt($io, $files), |
| 163 |
'json' => $this->displayJson($io, $files), |
| 164 |
'github' => $this->displayTxt($io, $files, true), |
| 165 |
default => throw new InvalidArgumentException(\sprintf('Supported formats are "%s".', implode('", "', $this->getAvailableFormatOptions()))), |
| 166 |
}; |
| 167 |
} |
| 168 |
|
| 169 |
private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false): int |
| 170 |
{ |
| 171 |
$countFiles = \count($filesInfo); |
| 172 |
$erroredFiles = 0; |
| 173 |
$githubReporter = $errorAsGithubAnnotations ? new GithubActionReporter($io) : null; |
| 174 |
|
| 175 |
foreach ($filesInfo as $info) { |
| 176 |
if ($info['valid'] && $this->displayCorrectFiles) { |
| 177 |
$io->comment('<info>OK</info>'.($info['file'] ? \sprintf(' in %s', $info['file']) : '')); |
| 178 |
} elseif (!$info['valid']) { |
| 179 |
++$erroredFiles; |
| 180 |
$io->text('<error> ERROR </error>'.($info['file'] ? \sprintf(' in %s', $info['file']) : '')); |
| 181 |
$io->listing(array_map(static function ($error) use ($info, $githubReporter) { |
| 182 |
|
| 183 |
$line = -1 === $error['line'] ? null : $error['line']; |
| 184 |
|
| 185 |
$githubReporter?->error($error['message'], $info['file'], $line, null !== $line ? $error['column'] : null); |
| 186 |
|
| 187 |
return null === $line ? $error['message'] : \sprintf('Line %d, Column %d: %s', $line, $error['column'], $error['message']); |
| 188 |
}, $info['messages'])); |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
if (0 === $erroredFiles) { |
| 193 |
$io->success(\sprintf('All %d XLIFF files contain valid syntax.', $countFiles)); |
| 194 |
} else { |
| 195 |
$io->warning(\sprintf('%d XLIFF files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles)); |
| 196 |
} |
| 197 |
|
| 198 |
return min($erroredFiles, 1); |
| 199 |
} |
| 200 |
|
| 201 |
private function displayJson(SymfonyStyle $io, array $filesInfo): int |
| 202 |
{ |
| 203 |
$errors = 0; |
| 204 |
|
| 205 |
array_walk($filesInfo, static function (&$v) use (&$errors) { |
| 206 |
$v['file'] = (string) $v['file']; |
| 207 |
if (!$v['valid']) { |
| 208 |
++$errors; |
| 209 |
} |
| 210 |
}); |
| 211 |
|
| 212 |
$io->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES)); |
| 213 |
|
| 214 |
return min($errors, 1); |
| 215 |
} |
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
private function getFiles(string $fileOrDirectory): iterable |
| 221 |
{ |
| 222 |
if (is_file($fileOrDirectory)) { |
| 223 |
yield new \SplFileInfo($fileOrDirectory); |
| 224 |
|
| 225 |
return; |
| 226 |
} |
| 227 |
|
| 228 |
foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) { |
| 229 |
if (!\in_array($file->getExtension(), ['xlf', 'xliff'], true)) { |
| 230 |
continue; |
| 231 |
} |
| 232 |
|
| 233 |
yield $file; |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
private function getDirectoryIterator(string $directory): iterable |
| 241 |
{ |
| 242 |
$default = static fn ($directory) => new \RecursiveIteratorIterator( |
| 243 |
new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS), |
| 244 |
\RecursiveIteratorIterator::LEAVES_ONLY |
| 245 |
); |
| 246 |
|
| 247 |
if (null !== $this->directoryIteratorProvider) { |
| 248 |
return ($this->directoryIteratorProvider)($directory, $default); |
| 249 |
} |
| 250 |
|
| 251 |
return $default($directory); |
| 252 |
} |
| 253 |
|
| 254 |
private function isReadable(string $fileOrDirectory): bool |
| 255 |
{ |
| 256 |
$default = static fn ($fileOrDirectory) => is_readable($fileOrDirectory); |
| 257 |
|
| 258 |
if (null !== $this->isReadableProvider) { |
| 259 |
return ($this->isReadableProvider)($fileOrDirectory, $default); |
| 260 |
} |
| 261 |
|
| 262 |
return $default($fileOrDirectory); |
| 263 |
} |
| 264 |
|
| 265 |
private function getTargetLanguageFromFile(\DOMDocument $xliffContents): ?string |
| 266 |
{ |
| 267 |
foreach ($xliffContents->getElementsByTagName('file')[0]->attributes ?? [] as $attribute) { |
| 268 |
if ('target-language' === $attribute->nodeName) { |
| 269 |
return $attribute->nodeValue; |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
return null; |
| 274 |
} |
| 275 |
|
| 276 |
public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void |
| 277 |
{ |
| 278 |
if ($input->mustSuggestOptionValuesFor('format')) { |
| 279 |
$suggestions->suggestValues($this->getAvailableFormatOptions()); |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
|
| 284 |
private function getAvailableFormatOptions(): array |
| 285 |
{ |
| 286 |
return ['txt', 'json', 'github']; |
| 287 |
} |
| 288 |
} |