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