vendor/symfony/translation/Command/XliffLintCommand.php line 109

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