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

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