暫無描述

LintCommand.php 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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\Yaml\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. use Symfony\Component\Yaml\Exception\ParseException;
  17. use Symfony\Component\Yaml\Parser;
  18. /**
  19. * Validates YAML files syntax and outputs encountered errors.
  20. *
  21. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  22. * @author Robin Chalas <robin.chalas@gmail.com>
  23. */
  24. class LintCommand extends Command
  25. {
  26. private $parser;
  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. ->setName('lint:yaml')
  44. ->setDescription('Lints a file and outputs encountered errors')
  45. ->addArgument('filename', null, 'A file or a directory or STDIN')
  46. ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')
  47. ->setHelp(<<<EOF
  48. The <info>%command.name%</info> command lints a YAML file and outputs to STDOUT
  49. the first encountered syntax error.
  50. You can validates YAML contents passed from STDIN:
  51. <info>cat filename | php %command.full_name%</info>
  52. You can also validate the syntax of a file:
  53. <info>php %command.full_name% filename</info>
  54. Or of a whole directory:
  55. <info>php %command.full_name% dirname</info>
  56. <info>php %command.full_name% dirname --format=json</info>
  57. EOF
  58. )
  59. ;
  60. }
  61. protected function execute(InputInterface $input, OutputInterface $output)
  62. {
  63. $io = new SymfonyStyle($input, $output);
  64. $filename = $input->getArgument('filename');
  65. $this->format = $input->getOption('format');
  66. $this->displayCorrectFiles = $output->isVerbose();
  67. if (!$filename) {
  68. if (!$stdin = $this->getStdin()) {
  69. throw new \RuntimeException('Please provide a filename or pipe file content to STDIN.');
  70. }
  71. return $this->display($io, array($this->validate($stdin)));
  72. }
  73. if (!$this->isReadable($filename)) {
  74. throw new \RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
  75. }
  76. $filesInfo = array();
  77. foreach ($this->getFiles($filename) as $file) {
  78. $filesInfo[] = $this->validate(file_get_contents($file), $file);
  79. }
  80. return $this->display($io, $filesInfo);
  81. }
  82. private function validate($content, $file = null)
  83. {
  84. try {
  85. $this->getParser()->parse($content);
  86. } catch (ParseException $e) {
  87. return array('file' => $file, 'valid' => false, 'message' => $e->getMessage());
  88. }
  89. return array('file' => $file, 'valid' => true);
  90. }
  91. private function display(SymfonyStyle $io, array $files)
  92. {
  93. switch ($this->format) {
  94. case 'txt':
  95. return $this->displayTxt($io, $files);
  96. case 'json':
  97. return $this->displayJson($io, $files);
  98. default:
  99. throw new \InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format));
  100. }
  101. }
  102. private function displayTxt(SymfonyStyle $io, array $filesInfo)
  103. {
  104. $countFiles = count($filesInfo);
  105. $erroredFiles = 0;
  106. foreach ($filesInfo as $info) {
  107. if ($info['valid'] && $this->displayCorrectFiles) {
  108. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  109. } elseif (!$info['valid']) {
  110. ++$erroredFiles;
  111. $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  112. $io->text(sprintf('<error> >> %s</error>', $info['message']));
  113. }
  114. }
  115. if ($erroredFiles === 0) {
  116. $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
  117. } else {
  118. $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles));
  119. }
  120. return min($erroredFiles, 1);
  121. }
  122. private function displayJson(SymfonyStyle $io, array $filesInfo)
  123. {
  124. $errors = 0;
  125. array_walk($filesInfo, function (&$v) use (&$errors) {
  126. $v['file'] = (string) $v['file'];
  127. if (!$v['valid']) {
  128. ++$errors;
  129. }
  130. });
  131. $io->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  132. return min($errors, 1);
  133. }
  134. private function getFiles($fileOrDirectory)
  135. {
  136. if (is_file($fileOrDirectory)) {
  137. yield new \SplFileInfo($fileOrDirectory);
  138. return;
  139. }
  140. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  141. if (!in_array($file->getExtension(), array('yml', 'yaml'))) {
  142. continue;
  143. }
  144. yield $file;
  145. }
  146. }
  147. private function getStdin()
  148. {
  149. if (0 !== ftell(STDIN)) {
  150. return;
  151. }
  152. $inputs = '';
  153. while (!feof(STDIN)) {
  154. $inputs .= fread(STDIN, 1024);
  155. }
  156. return $inputs;
  157. }
  158. private function getParser()
  159. {
  160. if (!$this->parser) {
  161. $this->parser = new Parser();
  162. }
  163. return $this->parser;
  164. }
  165. private function getDirectoryIterator($directory)
  166. {
  167. $default = function ($directory) {
  168. return new \RecursiveIteratorIterator(
  169. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  170. \RecursiveIteratorIterator::LEAVES_ONLY
  171. );
  172. };
  173. if (null !== $this->directoryIteratorProvider) {
  174. return call_user_func($this->directoryIteratorProvider, $directory, $default);
  175. }
  176. return $default($directory);
  177. }
  178. private function isReadable($fileOrDirectory)
  179. {
  180. $default = function ($fileOrDirectory) {
  181. return is_readable($fileOrDirectory);
  182. };
  183. if (null !== $this->isReadableProvider) {
  184. return call_user_func($this->isReadableProvider, $fileOrDirectory, $default);
  185. }
  186. return $default($fileOrDirectory);
  187. }
  188. }