LintCommand.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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\Exception\InvalidArgumentException;
  13. use Symfony\Component\Console\Exception\RuntimeException;
  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\Yaml\Exception\ParseException;
  19. use Symfony\Component\Yaml\Parser;
  20. use Symfony\Component\Yaml\Yaml;
  21. /**
  22. * Validates YAML files syntax and outputs encountered errors.
  23. *
  24. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  25. * @author Robin Chalas <robin.chalas@gmail.com>
  26. */
  27. class LintCommand extends Command
  28. {
  29. protected static $defaultName = 'lint:yaml';
  30. private $parser;
  31. private $format;
  32. private $displayCorrectFiles;
  33. private $directoryIteratorProvider;
  34. private $isReadableProvider;
  35. public function __construct($name = null, $directoryIteratorProvider = null, $isReadableProvider = null)
  36. {
  37. parent::__construct($name);
  38. $this->directoryIteratorProvider = $directoryIteratorProvider;
  39. $this->isReadableProvider = $isReadableProvider;
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. protected function configure()
  45. {
  46. $this
  47. ->setDescription('Lints a file and outputs encountered errors')
  48. ->addArgument('filename', null, 'A file or a directory or STDIN')
  49. ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')
  50. ->addOption('parse-tags', null, InputOption::VALUE_NONE, 'Parse custom tags')
  51. ->setHelp(<<<EOF
  52. The <info>%command.name%</info> command lints a YAML file and outputs to STDOUT
  53. the first encountered syntax error.
  54. You can validates YAML 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. $filename = $input->getArgument('filename');
  69. $this->format = $input->getOption('format');
  70. $this->displayCorrectFiles = $output->isVerbose();
  71. $flags = $input->getOption('parse-tags') ? Yaml::PARSE_CUSTOM_TAGS : 0;
  72. if (!$filename) {
  73. if (!$stdin = $this->getStdin()) {
  74. throw new RuntimeException('Please provide a filename or pipe file content to STDIN.');
  75. }
  76. return $this->display($io, array($this->validate($stdin, $flags)));
  77. }
  78. if (!$this->isReadable($filename)) {
  79. throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
  80. }
  81. $filesInfo = array();
  82. foreach ($this->getFiles($filename) as $file) {
  83. $filesInfo[] = $this->validate(file_get_contents($file), $flags, $file);
  84. }
  85. return $this->display($io, $filesInfo);
  86. }
  87. private function validate($content, $flags, $file = null)
  88. {
  89. $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  90. if (E_USER_DEPRECATED === $level) {
  91. throw new ParseException($message, $this->getParser()->getRealCurrentLineNb() + 1);
  92. }
  93. return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
  94. });
  95. try {
  96. $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
  97. } catch (ParseException $e) {
  98. return array('file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage());
  99. } finally {
  100. restore_error_handler();
  101. }
  102. return array('file' => $file, 'valid' => true);
  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->text(sprintf('<error> >> %s</error>', $info['message']));
  126. }
  127. }
  128. if (0 === $erroredFiles) {
  129. $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
  130. } else {
  131. $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles));
  132. }
  133. return min($erroredFiles, 1);
  134. }
  135. private function displayJson(SymfonyStyle $io, array $filesInfo)
  136. {
  137. $errors = 0;
  138. array_walk($filesInfo, function (&$v) use (&$errors) {
  139. $v['file'] = (string) $v['file'];
  140. if (!$v['valid']) {
  141. ++$errors;
  142. }
  143. });
  144. $io->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  145. return min($errors, 1);
  146. }
  147. private function getFiles($fileOrDirectory)
  148. {
  149. if (is_file($fileOrDirectory)) {
  150. yield new \SplFileInfo($fileOrDirectory);
  151. return;
  152. }
  153. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  154. if (!\in_array($file->getExtension(), array('yml', 'yaml'))) {
  155. continue;
  156. }
  157. yield $file;
  158. }
  159. }
  160. private function getStdin()
  161. {
  162. if (0 !== ftell(STDIN)) {
  163. return;
  164. }
  165. $inputs = '';
  166. while (!feof(STDIN)) {
  167. $inputs .= fread(STDIN, 1024);
  168. }
  169. return $inputs;
  170. }
  171. private function getParser()
  172. {
  173. if (!$this->parser) {
  174. $this->parser = new Parser();
  175. }
  176. return $this->parser;
  177. }
  178. private function getDirectoryIterator($directory)
  179. {
  180. $default = function ($directory) {
  181. return new \RecursiveIteratorIterator(
  182. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  183. \RecursiveIteratorIterator::LEAVES_ONLY
  184. );
  185. };
  186. if (null !== $this->directoryIteratorProvider) {
  187. return \call_user_func($this->directoryIteratorProvider, $directory, $default);
  188. }
  189. return $default($directory);
  190. }
  191. private function isReadable($fileOrDirectory)
  192. {
  193. $default = function ($fileOrDirectory) {
  194. return is_readable($fileOrDirectory);
  195. };
  196. if (null !== $this->isReadableProvider) {
  197. return \call_user_func($this->isReadableProvider, $fileOrDirectory, $default);
  198. }
  199. return $default($fileOrDirectory);
  200. }
  201. }