TranslationPullCommand.php
2 months ago
TranslationPushCommand.php
2 months ago
TranslationTrait.php
2 months ago
XliffLintCommand.php
2 months ago
XliffLintCommand.php
226 lines
| 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 | namespace ProfilePressVendor\Symfony\Component\Translation\Command; |
| 12 | |
| 13 | use ProfilePressVendor\Symfony\Component\Console\CI\GithubActionReporter; |
| 14 | use ProfilePressVendor\Symfony\Component\Console\Command\Command; |
| 15 | use ProfilePressVendor\Symfony\Component\Console\Completion\CompletionInput; |
| 16 | use ProfilePressVendor\Symfony\Component\Console\Completion\CompletionSuggestions; |
| 17 | use ProfilePressVendor\Symfony\Component\Console\Exception\RuntimeException; |
| 18 | use ProfilePressVendor\Symfony\Component\Console\Input\InputArgument; |
| 19 | use ProfilePressVendor\Symfony\Component\Console\Input\InputInterface; |
| 20 | use ProfilePressVendor\Symfony\Component\Console\Input\InputOption; |
| 21 | use ProfilePressVendor\Symfony\Component\Console\Output\OutputInterface; |
| 22 | use ProfilePressVendor\Symfony\Component\Console\Style\SymfonyStyle; |
| 23 | use ProfilePressVendor\Symfony\Component\Translation\Exception\InvalidArgumentException; |
| 24 | use ProfilePressVendor\Symfony\Component\Translation\Util\XliffUtils; |
| 25 | /** |
| 26 | * Validates XLIFF files syntax and outputs encountered errors. |
| 27 | * |
| 28 | * @author Grégoire Pineau <lyrixx@lyrixx.info> |
| 29 | * @author Robin Chalas <robin.chalas@gmail.com> |
| 30 | * @author Javier Eguiluz <javier.eguiluz@gmail.com> |
| 31 | */ |
| 32 | class XliffLintCommand extends Command |
| 33 | { |
| 34 | protected static $defaultName = 'lint:xliff'; |
| 35 | protected static $defaultDescription = 'Lint an XLIFF file and outputs encountered errors'; |
| 36 | private $format; |
| 37 | private $displayCorrectFiles; |
| 38 | private $directoryIteratorProvider; |
| 39 | private $isReadableProvider; |
| 40 | private $requireStrictFileNames; |
| 41 | public function __construct(?string $name = null, ?callable $directoryIteratorProvider = null, ?callable $isReadableProvider = null, bool $requireStrictFileNames = \true) |
| 42 | { |
| 43 | parent::__construct($name); |
| 44 | $this->directoryIteratorProvider = $directoryIteratorProvider; |
| 45 | $this->isReadableProvider = $isReadableProvider; |
| 46 | $this->requireStrictFileNames = $requireStrictFileNames; |
| 47 | } |
| 48 | /** |
| 49 | * {@inheritdoc} |
| 50 | */ |
| 51 | protected function configure() |
| 52 | { |
| 53 | $this->setDescription(self::$defaultDescription)->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from STDIN')->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format')->setHelp(<<<EOF |
| 54 | The <info>%command.name%</info> command lints an XLIFF file and outputs to STDOUT |
| 55 | the first encountered syntax error. |
| 56 | |
| 57 | You can validates XLIFF contents passed from STDIN: |
| 58 | |
| 59 | <info>cat filename | php %command.full_name% -</info> |
| 60 | |
| 61 | You can also validate the syntax of a file: |
| 62 | |
| 63 | <info>php %command.full_name% filename</info> |
| 64 | |
| 65 | Or of a whole directory: |
| 66 | |
| 67 | <info>php %command.full_name% dirname</info> |
| 68 | <info>php %command.full_name% dirname --format=json</info> |
| 69 | |
| 70 | EOF |
| 71 | ); |
| 72 | } |
| 73 | protected function execute(InputInterface $input, OutputInterface $output) |
| 74 | { |
| 75 | $io = new SymfonyStyle($input, $output); |
| 76 | $filenames = (array) $input->getArgument('filename'); |
| 77 | $this->format = $input->getOption('format') ?? (GithubActionReporter::isGithubActionEnvironment() ? 'github' : 'txt'); |
| 78 | $this->displayCorrectFiles = $output->isVerbose(); |
| 79 | if (['-'] === $filenames) { |
| 80 | return $this->display($io, [$this->validate(file_get_contents('php://stdin'))]); |
| 81 | } |
| 82 | if (!$filenames) { |
| 83 | throw new RuntimeException('Please provide a filename or pipe file content to STDIN.'); |
| 84 | } |
| 85 | $filesInfo = []; |
| 86 | foreach ($filenames as $filename) { |
| 87 | if (!$this->isReadable($filename)) { |
| 88 | throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename)); |
| 89 | } |
| 90 | foreach ($this->getFiles($filename) as $file) { |
| 91 | $filesInfo[] = $this->validate(file_get_contents($file), $file); |
| 92 | } |
| 93 | } |
| 94 | return $this->display($io, $filesInfo); |
| 95 | } |
| 96 | private function validate(string $content, ?string $file = null): array |
| 97 | { |
| 98 | $errors = []; |
| 99 | // Avoid: Warning DOMDocument::loadXML(): Empty string supplied as input |
| 100 | if ('' === trim($content)) { |
| 101 | return ['file' => $file, 'valid' => \true]; |
| 102 | } |
| 103 | $internal = libxml_use_internal_errors(\true); |
| 104 | $document = new \DOMDocument(); |
| 105 | $document->loadXML($content); |
| 106 | if (null !== $targetLanguage = $this->getTargetLanguageFromFile($document)) { |
| 107 | $normalizedLocalePattern = sprintf('(%s|%s)', preg_quote($targetLanguage, '/'), preg_quote(str_replace('-', '_', $targetLanguage), '/')); |
| 108 | // strict file names require translation files to be named '____.locale.xlf' |
| 109 | // otherwise, both '____.locale.xlf' and 'locale.____.xlf' are allowed |
| 110 | // also, the regexp matching must be case-insensitive, as defined for 'target-language' values |
| 111 | // http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#target-language |
| 112 | $expectedFilenamePattern = $this->requireStrictFileNames ? sprintf('/^.*\.(?i:%s)\.(?:xlf|xliff)/', $normalizedLocalePattern) : sprintf('/^(?:.*\.(?i:%s)|(?i:%s)\..*)\.(?:xlf|xliff)/', $normalizedLocalePattern, $normalizedLocalePattern); |
| 113 | if (0 === preg_match($expectedFilenamePattern, basename($file))) { |
| 114 | $errors[] = ['line' => -1, 'column' => -1, '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)]; |
| 115 | } |
| 116 | } |
| 117 | foreach (XliffUtils::validateSchema($document) as $xmlError) { |
| 118 | $errors[] = ['line' => $xmlError['line'], 'column' => $xmlError['column'], 'message' => $xmlError['message']]; |
| 119 | } |
| 120 | libxml_clear_errors(); |
| 121 | libxml_use_internal_errors($internal); |
| 122 | return ['file' => $file, 'valid' => 0 === \count($errors), 'messages' => $errors]; |
| 123 | } |
| 124 | private function display(SymfonyStyle $io, array $files) |
| 125 | { |
| 126 | switch ($this->format) { |
| 127 | case 'txt': |
| 128 | return $this->displayTxt($io, $files); |
| 129 | case 'json': |
| 130 | return $this->displayJson($io, $files); |
| 131 | case 'github': |
| 132 | return $this->displayTxt($io, $files, \true); |
| 133 | default: |
| 134 | throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format)); |
| 135 | } |
| 136 | } |
| 137 | private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = \false) |
| 138 | { |
| 139 | $countFiles = \count($filesInfo); |
| 140 | $erroredFiles = 0; |
| 141 | $githubReporter = $errorAsGithubAnnotations ? new GithubActionReporter($io) : null; |
| 142 | foreach ($filesInfo as $info) { |
| 143 | if ($info['valid'] && $this->displayCorrectFiles) { |
| 144 | $io->comment('<info>OK</info>' . ($info['file'] ? sprintf(' in %s', $info['file']) : '')); |
| 145 | } elseif (!$info['valid']) { |
| 146 | ++$erroredFiles; |
| 147 | $io->text('<error> ERROR </error>' . ($info['file'] ? sprintf(' in %s', $info['file']) : '')); |
| 148 | $io->listing(array_map(function ($error) use ($info, $githubReporter) { |
| 149 | // general document errors have a '-1' line number |
| 150 | $line = -1 === $error['line'] ? null : $error['line']; |
| 151 | if ($githubReporter) { |
| 152 | $githubReporter->error($error['message'], $info['file'], $line, null !== $line ? $error['column'] : null); |
| 153 | } |
| 154 | return null === $line ? $error['message'] : sprintf('Line %d, Column %d: %s', $line, $error['column'], $error['message']); |
| 155 | }, $info['messages'])); |
| 156 | } |
| 157 | } |
| 158 | if (0 === $erroredFiles) { |
| 159 | $io->success(sprintf('All %d XLIFF files contain valid syntax.', $countFiles)); |
| 160 | } else { |
| 161 | $io->warning(sprintf('%d XLIFF files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles)); |
| 162 | } |
| 163 | return min($erroredFiles, 1); |
| 164 | } |
| 165 | private function displayJson(SymfonyStyle $io, array $filesInfo) |
| 166 | { |
| 167 | $errors = 0; |
| 168 | array_walk($filesInfo, function (&$v) use (&$errors) { |
| 169 | $v['file'] = (string) $v['file']; |
| 170 | if (!$v['valid']) { |
| 171 | ++$errors; |
| 172 | } |
| 173 | }); |
| 174 | $io->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES)); |
| 175 | return min($errors, 1); |
| 176 | } |
| 177 | private function getFiles(string $fileOrDirectory) |
| 178 | { |
| 179 | if (is_file($fileOrDirectory)) { |
| 180 | yield new \SplFileInfo($fileOrDirectory); |
| 181 | return; |
| 182 | } |
| 183 | foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) { |
| 184 | if (!\in_array($file->getExtension(), ['xlf', 'xliff'])) { |
| 185 | continue; |
| 186 | } |
| 187 | yield $file; |
| 188 | } |
| 189 | } |
| 190 | private function getDirectoryIterator(string $directory) |
| 191 | { |
| 192 | $default = function ($directory) { |
| 193 | return new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS), \RecursiveIteratorIterator::LEAVES_ONLY); |
| 194 | }; |
| 195 | if (null !== $this->directoryIteratorProvider) { |
| 196 | return ($this->directoryIteratorProvider)($directory, $default); |
| 197 | } |
| 198 | return $default($directory); |
| 199 | } |
| 200 | private function isReadable(string $fileOrDirectory) |
| 201 | { |
| 202 | $default = function ($fileOrDirectory) { |
| 203 | return is_readable($fileOrDirectory); |
| 204 | }; |
| 205 | if (null !== $this->isReadableProvider) { |
| 206 | return ($this->isReadableProvider)($fileOrDirectory, $default); |
| 207 | } |
| 208 | return $default($fileOrDirectory); |
| 209 | } |
| 210 | private function getTargetLanguageFromFile(\DOMDocument $xliffContents): ?string |
| 211 | { |
| 212 | foreach ($xliffContents->getElementsByTagName('file')[0]->attributes ?? [] as $attribute) { |
| 213 | if ('target-language' === $attribute->nodeName) { |
| 214 | return $attribute->nodeValue; |
| 215 | } |
| 216 | } |
| 217 | return null; |
| 218 | } |
| 219 | public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void |
| 220 | { |
| 221 | if ($input->mustSuggestOptionValuesFor('format')) { |
| 222 | $suggestions->suggestValues(['txt', 'json', 'github']); |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 |