Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

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