vendor/symfony/yaml/Command/LintCommand.php line 45

Open in your IDE?
  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\CI\GithubActionReporter;
  12. use Symfony\Component\Console\Attribute\AsCommand;
  13. use Symfony\Component\Console\Command\Command;
  14. use Symfony\Component\Console\Completion\CompletionInput;
  15. use Symfony\Component\Console\Completion\CompletionSuggestions;
  16. use Symfony\Component\Console\Exception\InvalidArgumentException;
  17. use Symfony\Component\Console\Exception\RuntimeException;
  18. use Symfony\Component\Console\Input\InputArgument;
  19. use Symfony\Component\Console\Input\InputInterface;
  20. use Symfony\Component\Console\Input\InputOption;
  21. use Symfony\Component\Console\Output\OutputInterface;
  22. use Symfony\Component\Console\Style\SymfonyStyle;
  23. use Symfony\Component\Yaml\Exception\ParseException;
  24. use Symfony\Component\Yaml\Parser;
  25. use Symfony\Component\Yaml\Yaml;
  26. /**
  27.  * Validates YAML files syntax and outputs encountered errors.
  28.  *
  29.  * @author GrĂ©goire Pineau <lyrixx@lyrixx.info>
  30.  * @author Robin Chalas <robin.chalas@gmail.com>
  31.  */
  32. #[AsCommand(name: 'lint:yaml', description: 'Lint a YAML file and outputs encountered errors')]
  33. class LintCommand extends Command
  34. {
  35.     private $parser;
  36.     private ?string $format = null;
  37.     private bool $displayCorrectFiles;
  38.     private ?\Closure $directoryIteratorProvider;
  39.     private ?\Closure $isReadableProvider;
  40.     public function __construct(string $name = null, callable $directoryIteratorProvider = null, callable $isReadableProvider = null)
  41.     {
  42.         parent::__construct($name);
  43.         $this->directoryIteratorProvider = null === $directoryIteratorProvider || $directoryIteratorProvider instanceof \Closure ? $directoryIteratorProvider : \Closure::fromCallable($directoryIteratorProvider);
  44.         $this->isReadableProvider = null === $isReadableProvider || $isReadableProvider instanceof \Closure ? $isReadableProvider : \Closure::fromCallable($isReadableProvider);
  45.     }
  46.     /**
  47.      * {@inheritdoc}
  48.      */
  49.     protected function configure()
  50.     {
  51.         $this
  52.             ->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from STDIN')
  53.             ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format')
  54.             ->addOption('exclude', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Path(s) to exclude')
  55.             ->addOption('parse-tags', null, InputOption::VALUE_NEGATABLE, 'Parse custom tags', null)
  56.             ->setHelp(<<<EOF
  57. The <info>%command.name%</info> command lints a YAML file and outputs to STDOUT
  58. the first encountered syntax error.
  59. You can validates YAML contents passed from STDIN:
  60.   <info>cat filename | php %command.full_name% -</info>
  61. You can also validate the syntax of a file:
  62.   <info>php %command.full_name% filename</info>
  63. Or of a whole directory:
  64.   <info>php %command.full_name% dirname</info>
  65.   <info>php %command.full_name% dirname --format=json</info>
  66. You can also exclude one or more specific files:
  67.   <info>php %command.full_name% dirname --exclude="dirname/foo.yaml" --exclude="dirname/bar.yaml"</info>
  68. EOF
  69.             )
  70.         ;
  71.     }
  72.     protected function execute(InputInterface $input, OutputInterface $output): int
  73.     {
  74.         $io = new SymfonyStyle($input, $output);
  75.         $filenames = (array) $input->getArgument('filename');
  76.         $excludes = $input->getOption('exclude');
  77.         $this->format = $input->getOption('format');
  78.         $flags = $input->getOption('parse-tags');
  79.         if ('github' === $this->format && !class_exists(GithubActionReporter::class)) {
  80.             throw new \InvalidArgumentException('The "github" format is only available since "symfony/console" >= 5.3.');
  81.         }
  82.         if (null === $this->format) {
  83.             // Autodetect format according to CI environment
  84.             $this->format = class_exists(GithubActionReporter::class) && GithubActionReporter::isGithubActionEnvironment() ? 'github' : 'txt';
  85.         }
  86.         $flags = $flags ? Yaml::PARSE_CUSTOM_TAGS : 0;
  87.         $this->displayCorrectFiles = $output->isVerbose();
  88.         if (['-'] === $filenames) {
  89.             return $this->display($io, [$this->validate(file_get_contents('php://stdin'), $flags)]);
  90.         }
  91.         if (!$filenames) {
  92.             throw new RuntimeException('Please provide a filename or pipe file content to STDIN.');
  93.         }
  94.         $filesInfo = [];
  95.         foreach ($filenames as $filename) {
  96.             if (!$this->isReadable($filename)) {
  97.                 throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
  98.             }
  99.             foreach ($this->getFiles($filename) as $file) {
  100.                 if (!\in_array($file->getPathname(), $excludes, true)) {
  101.                     $filesInfo[] = $this->validate(file_get_contents($file), $flags, $file);
  102.                 }
  103.             }
  104.         }
  105.         return $this->display($io, $filesInfo);
  106.     }
  107.     private function validate(string $content, int $flags, string $file = null)
  108.     {
  109.         $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  110.             if (\E_USER_DEPRECATED === $level) {
  111.                 throw new ParseException($message, $this->getParser()->getRealCurrentLineNb() + 1);
  112.             }
  113.             return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
  114.         });
  115.         try {
  116.             $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
  117.         } catch (ParseException $e) {
  118.             return ['file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage()];
  119.         } finally {
  120.             restore_error_handler();
  121.         }
  122.         return ['file' => $file, 'valid' => true];
  123.     }
  124.     private function display(SymfonyStyle $io, array $files): int
  125.     {
  126.         switch ($this->format) {
  127.             case 'txt':
  128.                 return $this->displayTxt($io, $files);
  129.             case 'json':
  130.                 return $this->displayJson($io, $files);
  131.             case 'github':
  132.                 return $this->displayTxt($io, $files, true);
  133.             default:
  134.                 throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format));
  135.         }
  136.     }
  137.     private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false): int
  138.     {
  139.         $countFiles = \count($filesInfo);
  140.         $erroredFiles = 0;
  141.         $suggestTagOption = false;
  142.         if ($errorAsGithubAnnotations) {
  143.             $githubReporter = new GithubActionReporter($io);
  144.         }
  145.         foreach ($filesInfo as $info) {
  146.             if ($info['valid'] && $this->displayCorrectFiles) {
  147.                 $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  148.             } elseif (!$info['valid']) {
  149.                 ++$erroredFiles;
  150.                 $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  151.                 $io->text(sprintf('<error> >> %s</error>', $info['message']));
  152.                 if (false !== strpos($info['message'], 'PARSE_CUSTOM_TAGS')) {
  153.                     $suggestTagOption = true;
  154.                 }
  155.                 if ($errorAsGithubAnnotations) {
  156.                     $githubReporter->error($info['message'], $info['file'] ?? 'php://stdin', $info['line']);
  157.                 }
  158.             }
  159.         }
  160.         if (0 === $erroredFiles) {
  161.             $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
  162.         } else {
  163.             $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.' : ''));
  164.         }
  165.         return min($erroredFiles, 1);
  166.     }
  167.     private function displayJson(SymfonyStyle $io, array $filesInfo): int
  168.     {
  169.         $errors = 0;
  170.         array_walk($filesInfo, function (&$v) use (&$errors) {
  171.             $v['file'] = (string) $v['file'];
  172.             if (!$v['valid']) {
  173.                 ++$errors;
  174.             }
  175.             if (isset($v['message']) && false !== strpos($v['message'], 'PARSE_CUSTOM_TAGS')) {
  176.                 $v['message'] .= ' Use the --parse-tags option if you want parse custom tags.';
  177.             }
  178.         });
  179.         $io->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
  180.         return min($errors, 1);
  181.     }
  182.     private function getFiles(string $fileOrDirectory): iterable
  183.     {
  184.         if (is_file($fileOrDirectory)) {
  185.             yield new \SplFileInfo($fileOrDirectory);
  186.             return;
  187.         }
  188.         foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  189.             if (!\in_array($file->getExtension(), ['yml', 'yaml'])) {
  190.                 continue;
  191.             }
  192.             yield $file;
  193.         }
  194.     }
  195.     private function getParser(): Parser
  196.     {
  197.         return $this->parser ??= new Parser();
  198.     }
  199.     private function getDirectoryIterator(string $directory): iterable
  200.     {
  201.         $default = function ($directory) {
  202.             return new \RecursiveIteratorIterator(
  203.                 new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  204.                 \RecursiveIteratorIterator::LEAVES_ONLY
  205.             );
  206.         };
  207.         if (null !== $this->directoryIteratorProvider) {
  208.             return ($this->directoryIteratorProvider)($directory, $default);
  209.         }
  210.         return $default($directory);
  211.     }
  212.     private function isReadable(string $fileOrDirectory): bool
  213.     {
  214.         $default = function ($fileOrDirectory) {
  215.             return is_readable($fileOrDirectory);
  216.         };
  217.         if (null !== $this->isReadableProvider) {
  218.             return ($this->isReadableProvider)($fileOrDirectory, $default);
  219.         }
  220.         return $default($fileOrDirectory);
  221.     }
  222.     public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
  223.     {
  224.         if ($input->mustSuggestOptionValuesFor('format')) {
  225.             $suggestions->suggestValues(['txt', 'json', 'github']);
  226.         }
  227.     }
  228. }