YamlLintCommand.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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\Bundle\FrameworkBundle\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\Finder\Finder;
  17. use Symfony\Component\Yaml\Exception\ParseException;
  18. use Symfony\Component\Yaml\Parser;
  19. /**
  20. * Validates YAML files syntax and outputs encountered errors.
  21. *
  22. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  23. */
  24. class YamlLintCommand extends Command
  25. {
  26. protected function configure()
  27. {
  28. $this
  29. ->setName('lint:yaml')
  30. ->setAliases(array('yaml:lint'))
  31. ->setDescription('Lints a file and outputs encountered errors')
  32. ->addArgument('filename', null, 'A file or a directory or STDIN')
  33. ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')
  34. ->setHelp(<<<'EOF'
  35. The <info>%command.name%</info> command lints a YAML file and outputs to STDOUT
  36. the first encountered syntax error.
  37. You can validate the syntax of a file:
  38. <info>php %command.full_name% filename</info>
  39. Or of a whole directory:
  40. <info>php %command.full_name% dirname</info>
  41. <info>php %command.full_name% dirname --format=json</info>
  42. Or all YAML files in a bundle:
  43. <info>php %command.full_name% @AcmeDemoBundle</info>
  44. You can also pass the YAML contents from STDIN:
  45. <info>cat filename | php %command.full_name%</info>
  46. EOF
  47. )
  48. ;
  49. }
  50. protected function execute(InputInterface $input, OutputInterface $output)
  51. {
  52. $io = new SymfonyStyle($input, $output);
  53. if (false !== strpos($input->getFirstArgument(), ':l')) {
  54. $io->caution('The use of "yaml:lint" command is deprecated since version 2.7 and will be removed in 3.0. Use the "lint:yaml" instead.');
  55. }
  56. $filename = $input->getArgument('filename');
  57. if (!$filename) {
  58. if (0 !== ftell(STDIN)) {
  59. throw new \RuntimeException('Please provide a filename or pipe file content to STDIN.');
  60. }
  61. $content = '';
  62. while (!feof(STDIN)) {
  63. $content .= fread(STDIN, 1024);
  64. }
  65. return $this->display($input, $output, $io, array($this->validate($content)));
  66. }
  67. if (0 !== strpos($filename, '@') && !is_readable($filename)) {
  68. throw new \RuntimeException(sprintf('File or directory "%s" is not readable', $filename));
  69. }
  70. if (is_file($filename)) {
  71. $files = array($filename);
  72. } elseif (is_dir($filename)) {
  73. $files = Finder::create()->files()->in($filename)->name('*.yml');
  74. } else {
  75. $dir = $this->getApplication()->getKernel()->locateResource($filename);
  76. $files = Finder::create()->files()->in($dir)->name('*.yml');
  77. }
  78. $filesInfo = array();
  79. foreach ($files as $file) {
  80. $filesInfo[] = $this->validate(file_get_contents($file), $file);
  81. }
  82. return $this->display($input, $output, $io, $filesInfo);
  83. }
  84. private function validate($content, $file = null)
  85. {
  86. $parser = new Parser();
  87. try {
  88. $parser->parse($content);
  89. } catch (ParseException $e) {
  90. return array('file' => $file, 'valid' => false, 'message' => $e->getMessage());
  91. }
  92. return array('file' => $file, 'valid' => true);
  93. }
  94. private function display(InputInterface $input, OutputInterface $output, SymfonyStyle $io, $files)
  95. {
  96. switch ($input->getOption('format')) {
  97. case 'txt':
  98. return $this->displayTxt($output, $io, $files);
  99. case 'json':
  100. return $this->displayJson($io, $files);
  101. default:
  102. throw new \InvalidArgumentException(sprintf('The format "%s" is not supported.', $input->getOption('format')));
  103. }
  104. }
  105. private function displayTxt(OutputInterface $output, SymfonyStyle $io, $filesInfo)
  106. {
  107. $errors = 0;
  108. foreach ($filesInfo as $info) {
  109. if ($info['valid'] && $output->isVerbose()) {
  110. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  111. } elseif (!$info['valid']) {
  112. ++$errors;
  113. $io->text(sprintf('<error> ERROR </error> in %s', $info['file']));
  114. $io->text(sprintf('<error> >> %s</error>', $info['message']));
  115. }
  116. }
  117. if (0 === $errors) {
  118. $io->success(sprintf('All %d YAML files contain valid syntax.', \count($filesInfo)));
  119. } else {
  120. $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.', \count($filesInfo) - $errors, $errors));
  121. }
  122. return min($errors, 1);
  123. }
  124. private function displayJson(OutputInterface $output, $filesInfo)
  125. {
  126. $errors = 0;
  127. array_walk($filesInfo, function (&$v) use (&$errors) {
  128. $v['file'] = (string) $v['file'];
  129. if (!$v['valid']) {
  130. ++$errors;
  131. }
  132. });
  133. $output->writeln(json_encode($filesInfo, \defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES : 0));
  134. return min($errors, 1);
  135. }
  136. }