XliffLintCommand.php 7.5 KB

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