菜谱项目

LintCommand.php 7.5KB

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\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. ->addOption('parse-tags', null, InputOption::VALUE_NONE, 'Parse custom tags')
  49. ->setHelp(<<<EOF
  50. The <info>%command.name%</info> command lints a YAML file and outputs to STDOUT
  51. the first encountered syntax error.
  52. You can validates YAML contents passed from STDIN:
  53. <info>cat filename | php %command.full_name%</info>
  54. You can also validate the syntax of a file:
  55. <info>php %command.full_name% filename</info>
  56. Or of a whole directory:
  57. <info>php %command.full_name% dirname</info>
  58. <info>php %command.full_name% dirname --format=json</info>
  59. EOF
  60. )
  61. ;
  62. }
  63. protected function execute(InputInterface $input, OutputInterface $output)
  64. {
  65. $io = new SymfonyStyle($input, $output);
  66. $filename = $input->getArgument('filename');
  67. $this->format = $input->getOption('format');
  68. $this->displayCorrectFiles = $output->isVerbose();
  69. $flags = $input->getOption('parse-tags') ? Yaml::PARSE_CUSTOM_TAGS : 0;
  70. if (!$filename) {
  71. if (!$stdin = $this->getStdin()) {
  72. throw new \RuntimeException('Please provide a filename or pipe file content to STDIN.');
  73. }
  74. return $this->display($io, array($this->validate($stdin, $flags)));
  75. }
  76. if (!$this->isReadable($filename)) {
  77. throw new \RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
  78. }
  79. $filesInfo = array();
  80. foreach ($this->getFiles($filename) as $file) {
  81. $filesInfo[] = $this->validate(file_get_contents($file), $flags, $file);
  82. }
  83. return $this->display($io, $filesInfo);
  84. }
  85. private function validate($content, $flags, $file = null)
  86. {
  87. $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  88. if (E_USER_DEPRECATED === $level) {
  89. throw new ParseException($message);
  90. }
  91. return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
  92. });
  93. try {
  94. $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
  95. } catch (ParseException $e) {
  96. return array('file' => $file, 'valid' => false, 'message' => $e->getMessage());
  97. } finally {
  98. restore_error_handler();
  99. }
  100. return array('file' => $file, 'valid' => true);
  101. }
  102. private function display(SymfonyStyle $io, array $files)
  103. {
  104. switch ($this->format) {
  105. case 'txt':
  106. return $this->displayTxt($io, $files);
  107. case 'json':
  108. return $this->displayJson($io, $files);
  109. default:
  110. throw new \InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format));
  111. }
  112. }
  113. private function displayTxt(SymfonyStyle $io, array $filesInfo)
  114. {
  115. $countFiles = count($filesInfo);
  116. $erroredFiles = 0;
  117. foreach ($filesInfo as $info) {
  118. if ($info['valid'] && $this->displayCorrectFiles) {
  119. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  120. } elseif (!$info['valid']) {
  121. ++$erroredFiles;
  122. $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  123. $io->text(sprintf('<error> >> %s</error>', $info['message']));
  124. }
  125. }
  126. if (0 === $erroredFiles) {
  127. $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
  128. } else {
  129. $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles));
  130. }
  131. return min($erroredFiles, 1);
  132. }
  133. private function displayJson(SymfonyStyle $io, array $filesInfo)
  134. {
  135. $errors = 0;
  136. array_walk($filesInfo, function (&$v) use (&$errors) {
  137. $v['file'] = (string) $v['file'];
  138. if (!$v['valid']) {
  139. ++$errors;
  140. }
  141. });
  142. $io->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  143. return min($errors, 1);
  144. }
  145. private function getFiles($fileOrDirectory)
  146. {
  147. if (is_file($fileOrDirectory)) {
  148. yield new \SplFileInfo($fileOrDirectory);
  149. return;
  150. }
  151. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  152. if (!in_array($file->getExtension(), array('yml', 'yaml'))) {
  153. continue;
  154. }
  155. yield $file;
  156. }
  157. }
  158. private function getStdin()
  159. {
  160. if (0 !== ftell(STDIN)) {
  161. return;
  162. }
  163. $inputs = '';
  164. while (!feof(STDIN)) {
  165. $inputs .= fread(STDIN, 1024);
  166. }
  167. return $inputs;
  168. }
  169. private function getParser()
  170. {
  171. if (!$this->parser) {
  172. $this->parser = new Parser();
  173. }
  174. return $this->parser;
  175. }
  176. private function getDirectoryIterator($directory)
  177. {
  178. $default = function ($directory) {
  179. return new \RecursiveIteratorIterator(
  180. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  181. \RecursiveIteratorIterator::LEAVES_ONLY
  182. );
  183. };
  184. if (null !== $this->directoryIteratorProvider) {
  185. return call_user_func($this->directoryIteratorProvider, $directory, $default);
  186. }
  187. return $default($directory);
  188. }
  189. private function isReadable($fileOrDirectory)
  190. {
  191. $default = function ($fileOrDirectory) {
  192. return is_readable($fileOrDirectory);
  193. };
  194. if (null !== $this->isReadableProvider) {
  195. return call_user_func($this->isReadableProvider, $fileOrDirectory, $default);
  196. }
  197. return $default($fileOrDirectory);
  198. }
  199. }