XliffLintCommand.php 9.7 KB

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