XliffLintCommand.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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($name = null, $directoryIteratorProvider = null, $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. // Avoid: Warning DOMDocument::loadXML(): Empty string supplied as input
  84. if ('' === trim($content)) {
  85. return array('file' => $file, 'valid' => true);
  86. }
  87. libxml_use_internal_errors(true);
  88. $document = new \DOMDocument();
  89. $document->loadXML($content);
  90. if ($document->schemaValidate(__DIR__.'/../Resources/schemas/xliff-core-1.2-strict.xsd')) {
  91. return array('file' => $file, 'valid' => true);
  92. }
  93. $errorMessages = array_map(function ($error) {
  94. return array(
  95. 'line' => $error->line,
  96. 'column' => $error->column,
  97. 'message' => trim($error->message),
  98. );
  99. }, libxml_get_errors());
  100. libxml_clear_errors();
  101. libxml_use_internal_errors(false);
  102. return array('file' => $file, 'valid' => false, 'messages' => $errorMessages);
  103. }
  104. private function display(SymfonyStyle $io, array $files)
  105. {
  106. switch ($this->format) {
  107. case 'txt':
  108. return $this->displayTxt($io, $files);
  109. case 'json':
  110. return $this->displayJson($io, $files);
  111. default:
  112. throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format));
  113. }
  114. }
  115. private function displayTxt(SymfonyStyle $io, array $filesInfo)
  116. {
  117. $countFiles = count($filesInfo);
  118. $erroredFiles = 0;
  119. foreach ($filesInfo as $info) {
  120. if ($info['valid'] && $this->displayCorrectFiles) {
  121. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  122. } elseif (!$info['valid']) {
  123. ++$erroredFiles;
  124. $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  125. $io->listing(array_map(function ($error) {
  126. // general document errors have a '-1' line number
  127. return -1 === $error['line'] ? $error['message'] : sprintf('Line %d, Column %d: %s', $error['line'], $error['column'], $error['message']);
  128. }, $info['messages']));
  129. }
  130. }
  131. if (0 === $erroredFiles) {
  132. $io->success(sprintf('All %d XLIFF files contain valid syntax.', $countFiles));
  133. } else {
  134. $io->warning(sprintf('%d XLIFF files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles));
  135. }
  136. return min($erroredFiles, 1);
  137. }
  138. private function displayJson(SymfonyStyle $io, array $filesInfo)
  139. {
  140. $errors = 0;
  141. array_walk($filesInfo, function (&$v) use (&$errors) {
  142. $v['file'] = (string) $v['file'];
  143. if (!$v['valid']) {
  144. ++$errors;
  145. }
  146. });
  147. $io->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  148. return min($errors, 1);
  149. }
  150. private function getFiles($fileOrDirectory)
  151. {
  152. if (is_file($fileOrDirectory)) {
  153. yield new \SplFileInfo($fileOrDirectory);
  154. return;
  155. }
  156. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  157. if (!in_array($file->getExtension(), array('xlf', 'xliff'))) {
  158. continue;
  159. }
  160. yield $file;
  161. }
  162. }
  163. private function getStdin()
  164. {
  165. if (0 !== ftell(STDIN)) {
  166. return;
  167. }
  168. $inputs = '';
  169. while (!feof(STDIN)) {
  170. $inputs .= fread(STDIN, 1024);
  171. }
  172. return $inputs;
  173. }
  174. private function getDirectoryIterator($directory)
  175. {
  176. $default = function ($directory) {
  177. return new \RecursiveIteratorIterator(
  178. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  179. \RecursiveIteratorIterator::LEAVES_ONLY
  180. );
  181. };
  182. if (null !== $this->directoryIteratorProvider) {
  183. return call_user_func($this->directoryIteratorProvider, $directory, $default);
  184. }
  185. return $default($directory);
  186. }
  187. private function isReadable($fileOrDirectory)
  188. {
  189. $default = function ($fileOrDirectory) {
  190. return is_readable($fileOrDirectory);
  191. };
  192. if (null !== $this->isReadableProvider) {
  193. return call_user_func($this->isReadableProvider, $fileOrDirectory, $default);
  194. }
  195. return $default($fileOrDirectory);
  196. }
  197. }