LintCommand.php 7.2 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. /**
  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. $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  85. if (E_USER_DEPRECATED === $level) {
  86. throw new ParseException($message);
  87. }
  88. return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
  89. });
  90. try {
  91. $this->getParser()->parse($content);
  92. } catch (ParseException $e) {
  93. return array('file' => $file, 'valid' => false, 'message' => $e->getMessage());
  94. } finally {
  95. restore_error_handler();
  96. }
  97. return array('file' => $file, 'valid' => true);
  98. }
  99. private function display(SymfonyStyle $io, array $files)
  100. {
  101. switch ($this->format) {
  102. case 'txt':
  103. return $this->displayTxt($io, $files);
  104. case 'json':
  105. return $this->displayJson($io, $files);
  106. default:
  107. throw new \InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format));
  108. }
  109. }
  110. private function displayTxt(SymfonyStyle $io, array $filesInfo)
  111. {
  112. $countFiles = count($filesInfo);
  113. $erroredFiles = 0;
  114. foreach ($filesInfo as $info) {
  115. if ($info['valid'] && $this->displayCorrectFiles) {
  116. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  117. } elseif (!$info['valid']) {
  118. ++$erroredFiles;
  119. $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  120. $io->text(sprintf('<error> >> %s</error>', $info['message']));
  121. }
  122. }
  123. if ($erroredFiles === 0) {
  124. $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
  125. } else {
  126. $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles));
  127. }
  128. return min($erroredFiles, 1);
  129. }
  130. private function displayJson(SymfonyStyle $io, array $filesInfo)
  131. {
  132. $errors = 0;
  133. array_walk($filesInfo, function (&$v) use (&$errors) {
  134. $v['file'] = (string) $v['file'];
  135. if (!$v['valid']) {
  136. ++$errors;
  137. }
  138. });
  139. $io->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  140. return min($errors, 1);
  141. }
  142. private function getFiles($fileOrDirectory)
  143. {
  144. if (is_file($fileOrDirectory)) {
  145. yield new \SplFileInfo($fileOrDirectory);
  146. return;
  147. }
  148. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  149. if (!in_array($file->getExtension(), array('yml', 'yaml'))) {
  150. continue;
  151. }
  152. yield $file;
  153. }
  154. }
  155. private function getStdin()
  156. {
  157. if (0 !== ftell(STDIN)) {
  158. return;
  159. }
  160. $inputs = '';
  161. while (!feof(STDIN)) {
  162. $inputs .= fread(STDIN, 1024);
  163. }
  164. return $inputs;
  165. }
  166. private function getParser()
  167. {
  168. if (!$this->parser) {
  169. $this->parser = new Parser();
  170. }
  171. return $this->parser;
  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. }