XliffLintCommand.php 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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\InputInterface;
  14. use Symfony\Component\Console\Input\InputOption;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. use Symfony\Component\Console\Style\SymfonyStyle;
  17. /**
  18. * Validates XLIFF files syntax and outputs encountered errors.
  19. *
  20. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  21. * @author Robin Chalas <robin.chalas@gmail.com>
  22. * @author Javier Eguiluz <javier.eguiluz@gmail.com>
  23. */
  24. class XliffLintCommand extends Command
  25. {
  26. protected static $defaultName = 'lint:xliff';
  27. private $format;
  28. private $displayCorrectFiles;
  29. private $directoryIteratorProvider;
  30. private $isReadableProvider;
  31. public function __construct(string $name = null, callable $directoryIteratorProvider = null, callable $isReadableProvider = null)
  32. {
  33. parent::__construct($name);
  34. $this->directoryIteratorProvider = $directoryIteratorProvider;
  35. $this->isReadableProvider = $isReadableProvider;
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. protected function configure()
  41. {
  42. $this
  43. ->setDescription('Lints a XLIFF file and outputs encountered errors')
  44. ->addArgument('filename', null, 'A file or a directory or STDIN')
  45. ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')
  46. ->setHelp(<<<EOF
  47. The <info>%command.name%</info> command lints a XLIFF file and outputs to STDOUT
  48. the first encountered syntax error.
  49. You can validates XLIFF contents passed from STDIN:
  50. <info>cat filename | php %command.full_name%</info>
  51. You can also validate the syntax of a file:
  52. <info>php %command.full_name% filename</info>
  53. Or of a whole directory:
  54. <info>php %command.full_name% dirname</info>
  55. <info>php %command.full_name% dirname --format=json</info>
  56. EOF
  57. )
  58. ;
  59. }
  60. protected function execute(InputInterface $input, OutputInterface $output)
  61. {
  62. $io = new SymfonyStyle($input, $output);
  63. $filename = $input->getArgument('filename');
  64. $this->format = $input->getOption('format');
  65. $this->displayCorrectFiles = $output->isVerbose();
  66. if (!$filename) {
  67. if (!$stdin = $this->getStdin()) {
  68. throw new RuntimeException('Please provide a filename or pipe file content to STDIN.');
  69. }
  70. return $this->display($io, array($this->validate($stdin)));
  71. }
  72. if (!$this->isReadable($filename)) {
  73. throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
  74. }
  75. $filesInfo = array();
  76. foreach ($this->getFiles($filename) as $file) {
  77. $filesInfo[] = $this->validate(file_get_contents($file), $file);
  78. }
  79. return $this->display($io, $filesInfo);
  80. }
  81. private function validate($content, $file = null)
  82. {
  83. $errors = array();
  84. // Avoid: Warning DOMDocument::loadXML(): Empty string supplied as input
  85. if ('' === trim($content)) {
  86. return array('file' => $file, 'valid' => true);
  87. }
  88. libxml_use_internal_errors(true);
  89. $document = new \DOMDocument();
  90. $document->loadXML($content);
  91. if (null !== $targetLanguage = $this->getTargetLanguageFromFile($document)) {
  92. $expectedFileExtension = sprintf('%s.xlf', str_replace('-', '_', $targetLanguage));
  93. $realFileExtension = explode('.', basename($file), 2)[1] ?? '';
  94. if ($expectedFileExtension !== $realFileExtension) {
  95. $errors[] = array(
  96. 'line' => -1,
  97. 'column' => -1,
  98. 'message' => sprintf('There is a mismatch between the file extension ("%s") and the "%s" value used in the "target-language" attribute of the file.', $realFileExtension, $targetLanguage),
  99. );
  100. }
  101. }
  102. $document->schemaValidate(__DIR__.'/../Resources/schemas/xliff-core-1.2-strict.xsd');
  103. foreach (libxml_get_errors() as $xmlError) {
  104. $errors[] = array(
  105. 'line' => $xmlError->line,
  106. 'column' => $xmlError->column,
  107. 'message' => trim($xmlError->message),
  108. );
  109. }
  110. libxml_clear_errors();
  111. libxml_use_internal_errors(false);
  112. return array('file' => $file, 'valid' => 0 === count($errors), 'messages' => $errors);
  113. }
  114. private function display(SymfonyStyle $io, array $files)
  115. {
  116. switch ($this->format) {
  117. case 'txt':
  118. return $this->displayTxt($io, $files);
  119. case 'json':
  120. return $this->displayJson($io, $files);
  121. default:
  122. throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format));
  123. }
  124. }
  125. private function displayTxt(SymfonyStyle $io, array $filesInfo)
  126. {
  127. $countFiles = count($filesInfo);
  128. $erroredFiles = 0;
  129. foreach ($filesInfo as $info) {
  130. if ($info['valid'] && $this->displayCorrectFiles) {
  131. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  132. } elseif (!$info['valid']) {
  133. ++$erroredFiles;
  134. $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  135. $io->listing(array_map(function ($error) {
  136. // general document errors have a '-1' line number
  137. return -1 === $error['line'] ? $error['message'] : sprintf('Line %d, Column %d: %s', $error['line'], $error['column'], $error['message']);
  138. }, $info['messages']));
  139. }
  140. }
  141. if (0 === $erroredFiles) {
  142. $io->success(sprintf('All %d XLIFF files contain valid syntax.', $countFiles));
  143. } else {
  144. $io->warning(sprintf('%d XLIFF files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles));
  145. }
  146. return min($erroredFiles, 1);
  147. }
  148. private function displayJson(SymfonyStyle $io, array $filesInfo)
  149. {
  150. $errors = 0;
  151. array_walk($filesInfo, function (&$v) use (&$errors) {
  152. $v['file'] = (string) $v['file'];
  153. if (!$v['valid']) {
  154. ++$errors;
  155. }
  156. });
  157. $io->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  158. return min($errors, 1);
  159. }
  160. private function getFiles($fileOrDirectory)
  161. {
  162. if (is_file($fileOrDirectory)) {
  163. yield new \SplFileInfo($fileOrDirectory);
  164. return;
  165. }
  166. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  167. if (!in_array($file->getExtension(), array('xlf', 'xliff'))) {
  168. continue;
  169. }
  170. yield $file;
  171. }
  172. }
  173. private function getStdin()
  174. {
  175. if (0 !== ftell(STDIN)) {
  176. return;
  177. }
  178. $inputs = '';
  179. while (!feof(STDIN)) {
  180. $inputs .= fread(STDIN, 1024);
  181. }
  182. return $inputs;
  183. }
  184. private function getDirectoryIterator($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 call_user_func($this->directoryIteratorProvider, $directory, $default);
  194. }
  195. return $default($directory);
  196. }
  197. private function isReadable($fileOrDirectory)
  198. {
  199. $default = function ($fileOrDirectory) {
  200. return is_readable($fileOrDirectory);
  201. };
  202. if (null !== $this->isReadableProvider) {
  203. return call_user_func($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 ?? array() as $attribute) {
  210. if ('target-language' === $attribute->nodeName) {
  211. return $attribute->nodeValue;
  212. }
  213. }
  214. return null;
  215. }
  216. }