LintCommand.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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('Lint a file and outputs encountered errors')
  49. ->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from 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 (['-'] === $filenames) {
  74. return $this->display($io, [$this->validate(file_get_contents('php://stdin'), $flags)]);
  75. }
  76. if (!$filenames) {
  77. throw new RuntimeException('Please provide a filename or pipe file content to STDIN.');
  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(string $content, int $flags, string $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): int
  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): int
  119. {
  120. $countFiles = \count($filesInfo);
  121. $erroredFiles = 0;
  122. $suggestTagOption = false;
  123. foreach ($filesInfo as $info) {
  124. if ($info['valid'] && $this->displayCorrectFiles) {
  125. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  126. } elseif (!$info['valid']) {
  127. ++$erroredFiles;
  128. $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  129. $io->text(sprintf('<error> >> %s</error>', $info['message']));
  130. if (false !== strpos($info['message'], 'PARSE_CUSTOM_TAGS')) {
  131. $suggestTagOption = true;
  132. }
  133. }
  134. }
  135. if (0 === $erroredFiles) {
  136. $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
  137. } else {
  138. $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.%s', $countFiles - $erroredFiles, $erroredFiles, $suggestTagOption ? ' Use the --parse-tags option if you want parse custom tags.' : ''));
  139. }
  140. return min($erroredFiles, 1);
  141. }
  142. private function displayJson(SymfonyStyle $io, array $filesInfo): int
  143. {
  144. $errors = 0;
  145. array_walk($filesInfo, function (&$v) use (&$errors) {
  146. $v['file'] = (string) $v['file'];
  147. if (!$v['valid']) {
  148. ++$errors;
  149. }
  150. if (isset($v['message']) && false !== strpos($v['message'], 'PARSE_CUSTOM_TAGS')) {
  151. $v['message'] .= ' Use the --parse-tags option if you want parse custom tags.';
  152. }
  153. });
  154. $io->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
  155. return min($errors, 1);
  156. }
  157. private function getFiles(string $fileOrDirectory): iterable
  158. {
  159. if (is_file($fileOrDirectory)) {
  160. yield new \SplFileInfo($fileOrDirectory);
  161. return;
  162. }
  163. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  164. if (!\in_array($file->getExtension(), ['yml', 'yaml'])) {
  165. continue;
  166. }
  167. yield $file;
  168. }
  169. }
  170. private function getParser(): Parser
  171. {
  172. if (!$this->parser) {
  173. $this->parser = new Parser();
  174. }
  175. return $this->parser;
  176. }
  177. private function getDirectoryIterator(string $directory): iterable
  178. {
  179. $default = function ($directory) {
  180. return new \RecursiveIteratorIterator(
  181. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  182. \RecursiveIteratorIterator::LEAVES_ONLY
  183. );
  184. };
  185. if (null !== $this->directoryIteratorProvider) {
  186. return ($this->directoryIteratorProvider)($directory, $default);
  187. }
  188. return $default($directory);
  189. }
  190. private function isReadable(string $fileOrDirectory): bool
  191. {
  192. $default = function ($fileOrDirectory) {
  193. return is_readable($fileOrDirectory);
  194. };
  195. if (null !== $this->isReadableProvider) {
  196. return ($this->isReadableProvider)($fileOrDirectory, $default);
  197. }
  198. return $default($fileOrDirectory);
  199. }
  200. }