LintCommand.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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\InputArgument;
  15. use Symfony\Component\Console\Input\InputInterface;
  16. use Symfony\Component\Console\Input\InputOption;
  17. use Symfony\Component\Console\Output\OutputInterface;
  18. use Symfony\Component\Console\Style\SymfonyStyle;
  19. use Symfony\Component\Yaml\Exception\ParseException;
  20. use Symfony\Component\Yaml\Parser;
  21. use Symfony\Component\Yaml\Yaml;
  22. /**
  23. * Validates YAML files syntax and outputs encountered errors.
  24. *
  25. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  26. * @author Robin Chalas <robin.chalas@gmail.com>
  27. */
  28. class LintCommand extends Command
  29. {
  30. protected static $defaultName = 'lint:yaml';
  31. private $parser;
  32. private $format;
  33. private $displayCorrectFiles;
  34. private $directoryIteratorProvider;
  35. private $isReadableProvider;
  36. public function __construct(string $name = null, callable $directoryIteratorProvider = null, callable $isReadableProvider = null)
  37. {
  38. parent::__construct($name);
  39. $this->directoryIteratorProvider = $directoryIteratorProvider;
  40. $this->isReadableProvider = $isReadableProvider;
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. protected function configure()
  46. {
  47. $this
  48. ->setDescription('Lints a file and outputs encountered errors')
  49. ->addArgument('filename', InputArgument::IS_ARRAY, 'A file or a directory or STDIN')
  50. ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')
  51. ->addOption('parse-tags', null, InputOption::VALUE_NONE, 'Parse custom tags')
  52. ->setHelp(<<<EOF
  53. The <info>%command.name%</info> command lints a YAML file and outputs to STDOUT
  54. the first encountered syntax error.
  55. You can validates YAML contents passed from STDIN:
  56. <info>cat filename | php %command.full_name%</info>
  57. You can also validate the syntax of a file:
  58. <info>php %command.full_name% filename</info>
  59. Or of a whole directory:
  60. <info>php %command.full_name% dirname</info>
  61. <info>php %command.full_name% dirname --format=json</info>
  62. EOF
  63. )
  64. ;
  65. }
  66. protected function execute(InputInterface $input, OutputInterface $output)
  67. {
  68. $io = new SymfonyStyle($input, $output);
  69. $filenames = (array) $input->getArgument('filename');
  70. $this->format = $input->getOption('format');
  71. $this->displayCorrectFiles = $output->isVerbose();
  72. $flags = $input->getOption('parse-tags') ? Yaml::PARSE_CUSTOM_TAGS : 0;
  73. if (0 === \count($filenames)) {
  74. if (!$stdin = $this->getStdin()) {
  75. throw new RuntimeException('Please provide a filename or pipe file content to STDIN.');
  76. }
  77. return $this->display($io, [$this->validate($stdin, $flags)]);
  78. }
  79. $filesInfo = [];
  80. foreach ($filenames as $filename) {
  81. if (!$this->isReadable($filename)) {
  82. throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
  83. }
  84. foreach ($this->getFiles($filename) as $file) {
  85. $filesInfo[] = $this->validate(file_get_contents($file), $flags, $file);
  86. }
  87. }
  88. return $this->display($io, $filesInfo);
  89. }
  90. private function validate($content, $flags, $file = null)
  91. {
  92. $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  93. if (E_USER_DEPRECATED === $level) {
  94. throw new ParseException($message, $this->getParser()->getRealCurrentLineNb() + 1);
  95. }
  96. return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
  97. });
  98. try {
  99. $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
  100. } catch (ParseException $e) {
  101. return ['file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage()];
  102. } finally {
  103. restore_error_handler();
  104. }
  105. return ['file' => $file, 'valid' => true];
  106. }
  107. private function display(SymfonyStyle $io, array $files)
  108. {
  109. switch ($this->format) {
  110. case 'txt':
  111. return $this->displayTxt($io, $files);
  112. case 'json':
  113. return $this->displayJson($io, $files);
  114. default:
  115. throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format));
  116. }
  117. }
  118. private function displayTxt(SymfonyStyle $io, array $filesInfo)
  119. {
  120. $countFiles = \count($filesInfo);
  121. $erroredFiles = 0;
  122. foreach ($filesInfo as $info) {
  123. if ($info['valid'] && $this->displayCorrectFiles) {
  124. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  125. } elseif (!$info['valid']) {
  126. ++$erroredFiles;
  127. $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  128. $io->text(sprintf('<error> >> %s</error>', $info['message']));
  129. }
  130. }
  131. if (0 === $erroredFiles) {
  132. $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
  133. } else {
  134. $io->warning(sprintf('%d YAML 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(), ['yml', 'yaml'])) {
  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 getParser()
  175. {
  176. if (!$this->parser) {
  177. $this->parser = new Parser();
  178. }
  179. return $this->parser;
  180. }
  181. private function getDirectoryIterator($directory)
  182. {
  183. $default = function ($directory) {
  184. return new \RecursiveIteratorIterator(
  185. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  186. \RecursiveIteratorIterator::LEAVES_ONLY
  187. );
  188. };
  189. if (null !== $this->directoryIteratorProvider) {
  190. return ($this->directoryIteratorProvider)($directory, $default);
  191. }
  192. return $default($directory);
  193. }
  194. private function isReadable($fileOrDirectory)
  195. {
  196. $default = function ($fileOrDirectory) {
  197. return is_readable($fileOrDirectory);
  198. };
  199. if (null !== $this->isReadableProvider) {
  200. return ($this->isReadableProvider)($fileOrDirectory, $default);
  201. }
  202. return $default($fileOrDirectory);
  203. }
  204. }