-
Notifications
You must be signed in to change notification settings - Fork 506
/
Copy pathAnalyseCommand.php
779 lines (665 loc) · 29.1 KB
/
AnalyseCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
<?php declare(strict_types = 1);
namespace PHPStan\Command;
use Nette\DI\Config\Loader;
use Nette\FileNotFoundException;
use Nette\InvalidStateException;
use OndraM\CiDetector\CiDetector;
use PHPStan\Analyser\Ignore\BaselineIgnoredErrorHelper;
use PHPStan\Analyser\InternalError;
use PHPStan\Command\ErrorFormatter\BaselineNeonErrorFormatter;
use PHPStan\Command\ErrorFormatter\BaselinePhpErrorFormatter;
use PHPStan\Command\ErrorFormatter\ErrorFormatter;
use PHPStan\Command\Symfony\SymfonyOutput;
use PHPStan\Command\Symfony\SymfonyStyle;
use PHPStan\DependencyInjection\Container;
use PHPStan\Diagnose\DiagnoseExtension;
use PHPStan\Diagnose\PHPStanDiagnoseExtension;
use PHPStan\File\CouldNotWriteFileException;
use PHPStan\File\FileHelper;
use PHPStan\File\FileReader;
use PHPStan\File\FileWriter;
use PHPStan\File\ParentDirectoryRelativePathHelper;
use PHPStan\File\PathNotFoundException;
use PHPStan\File\RelativePathHelper;
use PHPStan\Internal\BytesHelper;
use PHPStan\Internal\DirectoryCreator;
use PHPStan\Internal\DirectoryCreatorException;
use PHPStan\ShouldNotHappenException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
use Throwable;
use function array_intersect;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_reverse;
use function array_unique;
use function array_values;
use function count;
use function dirname;
use function filesize;
use function fopen;
use function get_class;
use function implode;
use function in_array;
use function is_array;
use function is_bool;
use function is_file;
use function is_string;
use function pathinfo;
use function rewind;
use function sprintf;
use function str_contains;
use function stream_get_contents;
use function strlen;
use function substr;
use const PATHINFO_BASENAME;
use const PATHINFO_EXTENSION;
/**
* @phpstan-import-type Trace from InternalError as InternalErrorTrace
*/
final class AnalyseCommand extends Command
{
private const NAME = 'analyse';
public const OPTION_LEVEL = 'level';
public const DEFAULT_LEVEL = CommandHelper::DEFAULT_LEVEL;
/**
* @param string[] $composerAutoloaderProjectPaths
*/
public function __construct(
private array $composerAutoloaderProjectPaths,
private float $analysisStartTime,
)
{
parent::__construct();
}
protected function configure(): void
{
$this->setName(self::NAME)
->setDescription('Analyses source code')
->setDefinition([
new InputArgument('paths', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'Paths with source code to run analysis on'),
new InputOption('configuration', 'c', InputOption::VALUE_REQUIRED, 'Path to project configuration file'),
new InputOption(self::OPTION_LEVEL, 'l', InputOption::VALUE_REQUIRED, 'Level of rule options - the higher the stricter'),
new InputOption(ErrorsConsoleStyle::OPTION_NO_PROGRESS, null, InputOption::VALUE_NONE, 'Do not show progress bar, only results'),
new InputOption('debug', null, InputOption::VALUE_NONE, 'Show debug information - which file is analysed, do not catch internal errors'),
new InputOption('autoload-file', 'a', InputOption::VALUE_REQUIRED, 'Project\'s additional autoload file path'),
new InputOption('error-format', null, InputOption::VALUE_REQUIRED, 'Format in which to print the result of the analysis', null),
new InputOption('generate-baseline', 'b', InputOption::VALUE_OPTIONAL, 'Path to a file where the baseline should be saved', false),
new InputOption('allow-empty-baseline', null, InputOption::VALUE_NONE, 'Do not error out when the generated baseline is empty'),
new InputOption('memory-limit', null, InputOption::VALUE_REQUIRED, 'Memory limit for analysis'),
new InputOption('xdebug', null, InputOption::VALUE_NONE, 'Allow running with Xdebug for debugging purposes'),
new InputOption('fix', null, InputOption::VALUE_NONE, 'Launch PHPStan Pro'),
new InputOption('watch', null, InputOption::VALUE_NONE, 'Launch PHPStan Pro'),
new InputOption('pro', null, InputOption::VALUE_NONE, 'Launch PHPStan Pro'),
new InputOption('fail-without-result-cache', null, InputOption::VALUE_NONE, 'Return non-zero exit code when result cache is not used'),
new InputOption('only-remove-errors', null, InputOption::VALUE_NONE, 'Only remove existing errors from the baseline. Do not add new ones.'),
]);
}
/**
* @return string[]
*/
public function getAliases(): array
{
return ['analyze'];
}
protected function initialize(InputInterface $input, OutputInterface $output): void
{
if ((bool) $input->getOption('debug')) {
$application = $this->getApplication();
if ($application === null) {
return;
}
$application->setCatchExceptions(false);
return;
}
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$paths = $input->getArgument('paths');
$memoryLimit = $input->getOption('memory-limit');
$autoloadFile = $input->getOption('autoload-file');
$configuration = $input->getOption('configuration');
$level = $input->getOption(self::OPTION_LEVEL);
$allowXdebug = $input->getOption('xdebug');
$debugEnabled = (bool) $input->getOption('debug');
$fix = (bool) $input->getOption('fix') || (bool) $input->getOption('watch') || (bool) $input->getOption('pro');
$failWithoutResultCache = (bool) $input->getOption('fail-without-result-cache');
$onlyRemoveErrors = (bool) $input->getOption('only-remove-errors');
/** @var string|false|null $generateBaselineFile */
$generateBaselineFile = $input->getOption('generate-baseline');
if ($generateBaselineFile === false) {
$generateBaselineFile = null;
} elseif ($generateBaselineFile === null) {
$generateBaselineFile = 'phpstan-baseline.neon';
}
$allowEmptyBaseline = (bool) $input->getOption('allow-empty-baseline');
if (
!is_array($paths)
|| (!is_string($memoryLimit) && $memoryLimit !== null)
|| (!is_string($autoloadFile) && $autoloadFile !== null)
|| (!is_string($configuration) && $configuration !== null)
|| (!is_string($level) && $level !== null)
|| (!is_bool($allowXdebug))
) {
throw new ShouldNotHappenException();
}
try {
$inceptionResult = CommandHelper::begin(
$input,
$output,
$paths,
$memoryLimit,
$autoloadFile,
$this->composerAutoloaderProjectPaths,
$configuration,
$generateBaselineFile,
$level,
$allowXdebug,
$debugEnabled,
true,
);
} catch (InceptionNotSuccessfulException $e) {
return 1;
}
if ($generateBaselineFile === null && $allowEmptyBaseline) {
$inceptionResult->getStdOutput()->getStyle()->error('You must pass the --generate-baseline option alongside --allow-empty-baseline.');
return $inceptionResult->handleReturn(1, null, $this->analysisStartTime);
}
if ($generateBaselineFile === null && $onlyRemoveErrors) {
$inceptionResult->getStdOutput()->getStyle()->error('You must pass the --generate-baseline option alongside --only-remove-errors.');
return $inceptionResult->handleReturn(1, null, $this->analysisStartTime);
}
$errorOutput = $inceptionResult->getErrorOutput();
$errorFormat = $input->getOption('error-format');
if (!is_string($errorFormat) && $errorFormat !== null) {
throw new ShouldNotHappenException();
}
if ($errorFormat === null) {
$errorFormat = $inceptionResult->getContainer()->getParameter('errorFormat');
}
if ($errorFormat === null) {
$errorFormat = 'table';
}
$container = $inceptionResult->getContainer();
$errorFormatterServiceName = sprintf('errorFormatter.%s', $errorFormat);
if (!$container->hasService($errorFormatterServiceName)) {
$errorOutput->writeLineFormatted(sprintf(
'Error formatter "%s" not found. Available error formatters are: %s',
$errorFormat,
implode(', ', array_map(static fn (string $name): string => substr($name, strlen('errorFormatter.')), $container->findServiceNamesByType(ErrorFormatter::class))),
));
return 1;
}
$generateBaselineFile = $inceptionResult->getGenerateBaselineFile();
if ($generateBaselineFile !== null) {
$baselineExtension = pathinfo($generateBaselineFile, PATHINFO_EXTENSION);
if ($baselineExtension === '') {
$inceptionResult->getStdOutput()->getStyle()->error(sprintf('Baseline filename must have an extension, %s provided instead.', pathinfo($generateBaselineFile, PATHINFO_BASENAME)));
return $inceptionResult->handleReturn(1, null, $this->analysisStartTime);
}
if (!in_array($baselineExtension, ['neon', 'php'], true)) {
$inceptionResult->getStdOutput()->getStyle()->error(sprintf('Baseline filename extension must be .neon or .php, .%s was used instead.', $baselineExtension));
return $inceptionResult->handleReturn(1, null, $this->analysisStartTime);
}
}
try {
[$files, $onlyFiles] = $inceptionResult->getFiles();
} catch (PathNotFoundException $e) {
$this->runDiagnoseExtensions($container, $inceptionResult->getErrorOutput());
$inceptionResult->getErrorOutput()->writeLineFormatted(sprintf('<error>%s</error>', $e->getMessage()));
return 1;
} catch (InceptionNotSuccessfulException) {
$this->runDiagnoseExtensions($container, $inceptionResult->getErrorOutput());
return 1;
}
if (count($files) === 0) {
$this->runDiagnoseExtensions($container, $inceptionResult->getErrorOutput());
$inceptionResult->getErrorOutput()->getStyle()->error('No files found to analyse.');
return $inceptionResult->handleReturn(1, null, $this->analysisStartTime);
}
$analysedConfigFiles = array_intersect($files, $container->getParameter('allConfigFiles'));
/** @var RelativePathHelper $relativePathHelper */
$relativePathHelper = $container->getService('relativePathHelper');
foreach ($analysedConfigFiles as $analysedConfigFile) {
$fileSize = @filesize($analysedConfigFile);
if ($fileSize === false) {
continue;
}
if ($fileSize <= 512 * 1024) {
continue;
}
$inceptionResult->getErrorOutput()->getStyle()->warning(sprintf(
'Configuration file %s (%s) is too big and might slow down PHPStan. Consider adding it to excludePaths.',
$relativePathHelper->getRelativePath($analysedConfigFile),
BytesHelper::bytes($fileSize),
));
}
if ($fix) {
if ($generateBaselineFile !== null) {
$inceptionResult->getStdOutput()->getStyle()->error('You cannot pass the --generate-baseline option when running PHPStan Pro.');
return $inceptionResult->handleReturn(1, null, $this->analysisStartTime);
}
return $this->runFixer($inceptionResult, $container, $onlyFiles, $input, $output, $files);
}
/** @var AnalyseApplication $application */
$application = $container->getByType(AnalyseApplication::class);
$debug = $input->getOption('debug');
if (!is_bool($debug)) {
throw new ShouldNotHappenException();
}
try {
$analysisResult = $application->analyse(
$files,
$onlyFiles,
$inceptionResult->getStdOutput(),
$inceptionResult->getErrorOutput(),
$inceptionResult->isDefaultLevelUsed(),
$debug,
$inceptionResult->getProjectConfigFile(),
$inceptionResult->getProjectConfigArray(),
$input,
);
} catch (Throwable $t) {
if ($debug) {
$stdOutput = $inceptionResult->getStdOutput();
$stdOutput->writeRaw(sprintf(
'Uncaught %s: %s in %s:%d',
get_class($t),
$t->getMessage(),
$t->getFile(),
$t->getLine(),
));
$stdOutput->writeLineFormatted('');
$stdOutput->writeRaw($t->getTraceAsString());
$stdOutput->writeLineFormatted('');
$previous = $t->getPrevious();
while ($previous !== null) {
$stdOutput->writeLineFormatted('');
$stdOutput->writeLineFormatted('Caused by:');
$stdOutput->writeRaw(sprintf(
'Uncaught %s: %s in %s:%d',
get_class($previous),
$previous->getMessage(),
$previous->getFile(),
$previous->getLine(),
));
$stdOutput->writeRaw($previous->getTraceAsString());
$stdOutput->writeLineFormatted('');
$previous = $previous->getPrevious();
}
return $inceptionResult->handleReturn(1, null, $this->analysisStartTime);
}
throw $t;
}
/**
* Variable $internalErrorsTuples contains both "internal errors"
* and "errors with non-ignorable exception" as InternalError objects.
*/
$internalErrorsTuples = [];
$internalFileSpecificErrors = [];
foreach ($analysisResult->getInternalErrorObjects() as $internalError) {
$internalErrorsTuples[$internalError->getMessage()] = [new InternalError(
$internalError->getTraceAsString() !== null ? sprintf('Internal error: %s', $internalError->getMessage()) : $internalError->getMessage(),
$internalError->getContextDescription(),
$internalError->getTrace(),
$internalError->getTraceAsString(),
$internalError->shouldReportBug(),
), false];
}
foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) {
if (!$fileSpecificError->hasNonIgnorableException()) {
continue;
}
$message = $fileSpecificError->getMessage();
$metadata = $fileSpecificError->getMetadata();
$hasStackTrace = false;
if (
$fileSpecificError->getIdentifier() === 'phpstan.internal'
&& array_key_exists(InternalError::STACK_TRACE_AS_STRING_METADATA_KEY, $metadata)
) {
$message = sprintf('Internal error: %s', $message);
$hasStackTrace = true;
}
if (!$hasStackTrace) {
if (!array_key_exists($fileSpecificError->getMessage(), $internalFileSpecificErrors)) {
$internalFileSpecificErrors[$fileSpecificError->getMessage()] = $fileSpecificError;
}
}
$internalErrorsTuples[$fileSpecificError->getMessage()] = [new InternalError(
$message,
sprintf('analysing file %s', $fileSpecificError->getTraitFilePath() ?? $fileSpecificError->getFilePath()),
$metadata[InternalError::STACK_TRACE_METADATA_KEY] ?? [],
$metadata[InternalError::STACK_TRACE_AS_STRING_METADATA_KEY] ?? null,
true,
), !$hasStackTrace];
}
$internalErrorsTuples = array_values($internalErrorsTuples);
$fileHelper = $container->getByType(FileHelper::class);
/**
* Variable $internalErrors only contains non-file-specific "internal errors".
*/
$internalErrors = [];
foreach ($internalErrorsTuples as [$internalError, $isInFileSpecificErrors]) {
if ($isInFileSpecificErrors) {
continue;
}
$internalErrors[] = new InternalError(
$this->getMessageFromInternalError($fileHelper, $internalError, $output->getVerbosity()),
$internalError->getContextDescription(),
$internalError->getTrace(),
$internalError->getTraceAsString(),
$internalError->shouldReportBug(),
);
}
if ($generateBaselineFile !== null) {
$this->runDiagnoseExtensions($container, $inceptionResult->getErrorOutput());
if (count($internalErrorsTuples) > 0) {
foreach ($internalErrorsTuples as [$internalError]) {
$inceptionResult->getStdOutput()->writeLineFormatted($internalError->getMessage());
$inceptionResult->getStdOutput()->writeLineFormatted('');
}
$inceptionResult->getStdOutput()->getStyle()->error(sprintf(
'%s occurred. Baseline could not be generated.',
count($internalErrors) === 1 ? 'An internal error' : 'Internal errors',
));
return $inceptionResult->handleReturn(1, $analysisResult->getPeakMemoryUsageBytes(), $this->analysisStartTime);
}
return $this->generateBaseline($generateBaselineFile, $inceptionResult, $analysisResult, $output, $allowEmptyBaseline, $baselineExtension, $failWithoutResultCache, $onlyRemoveErrors, $container);
}
/** @var ErrorFormatter $errorFormatter */
$errorFormatter = $container->getService($errorFormatterServiceName);
if (count($internalErrorsTuples) > 0) {
$analysisResult = new AnalysisResult(
array_values($internalFileSpecificErrors),
array_map(static fn (InternalError $internalError) => $internalError->getMessage(), $internalErrors),
[],
[],
[],
$analysisResult->isDefaultLevelUsed(),
$analysisResult->getProjectConfigFile(),
$analysisResult->isResultCacheSaved(),
$analysisResult->getPeakMemoryUsageBytes(),
$analysisResult->isResultCacheUsed(),
$analysisResult->getChangedProjectExtensionFilesOutsideOfAnalysedPaths(),
);
$exitCode = $errorFormatter->formatErrors($analysisResult, $inceptionResult->getStdOutput());
$this->runDiagnoseExtensions($container, $inceptionResult->getErrorOutput());
$errorOutput->writeLineFormatted('⚠️ Result is incomplete because of severe errors. ⚠️');
$errorOutput->writeLineFormatted(' Fix these errors first and then re-run PHPStan');
$errorOutput->writeLineFormatted(' to get all reported errors.');
$errorOutput->writeLineFormatted('');
return $inceptionResult->handleReturn(
$exitCode,
$analysisResult->getPeakMemoryUsageBytes(),
$this->analysisStartTime,
);
}
$exitCode = $errorFormatter->formatErrors($analysisResult, $inceptionResult->getStdOutput());
if ($failWithoutResultCache && !$analysisResult->isResultCacheUsed()) {
$exitCode = 2;
}
if (
$analysisResult->isResultCacheUsed()
&& $analysisResult->isResultCacheSaved()
&& !$onlyFiles
&& $inceptionResult->getProjectConfigArray() !== null
) {
$projectServicesNotInAnalysedPaths = array_values(array_unique($analysisResult->getChangedProjectExtensionFilesOutsideOfAnalysedPaths()));
$projectServiceFileNamesNotInAnalysedPaths = array_keys($analysisResult->getChangedProjectExtensionFilesOutsideOfAnalysedPaths());
if (count($projectServicesNotInAnalysedPaths) > 0) {
$one = count($projectServicesNotInAnalysedPaths) === 1;
$errorOutput->writeLineFormatted('<comment>Result cache might not behave correctly.</comment>');
$errorOutput->writeLineFormatted(sprintf('You\'re using custom %s in your project config', $one ? 'extension' : 'extensions'));
$errorOutput->writeLineFormatted(sprintf('but %s not part of analysed paths:', $one ? 'this extension is' : 'these extensions are'));
$errorOutput->writeLineFormatted('');
foreach ($projectServicesNotInAnalysedPaths as $service) {
$errorOutput->writeLineFormatted(sprintf('- %s', $service));
}
$errorOutput->writeLineFormatted('');
$errorOutput->writeLineFormatted('When you edit them and re-run PHPStan, the result cache will get stale.');
$directoriesToAdd = [];
foreach ($projectServiceFileNamesNotInAnalysedPaths as $path) {
$directoriesToAdd[] = dirname($relativePathHelper->getRelativePath($path));
}
$directoriesToAdd = array_unique($directoriesToAdd);
$oneDirectory = count($directoriesToAdd) === 1;
$errorOutput->writeLineFormatted(sprintf('Add %s to your analysed paths to get rid of this problem:', $oneDirectory ? 'this directory' : 'these directories'));
$errorOutput->writeLineFormatted('');
foreach ($directoriesToAdd as $directory) {
$errorOutput->writeLineFormatted(sprintf('- %s', $directory));
}
$errorOutput->writeLineFormatted('');
return $inceptionResult->handleReturn(1, $analysisResult->getPeakMemoryUsageBytes(), $this->analysisStartTime);
}
}
$this->runDiagnoseExtensions($container, $inceptionResult->getErrorOutput());
return $inceptionResult->handleReturn(
$exitCode,
$analysisResult->getPeakMemoryUsageBytes(),
$this->analysisStartTime,
);
}
private function createStreamOutput(): StreamOutput
{
$resource = fopen('php://memory', 'w', false);
if ($resource === false) {
throw new ShouldNotHappenException();
}
return new StreamOutput($resource);
}
private function getMessageFromInternalError(FileHelper $fileHelper, InternalError $internalError, int $verbosity): string
{
$message = sprintf('%s while %s', $internalError->getMessage(), $internalError->getContextDescription());
$hasLarastan = false;
$isLaravelLast = false;
foreach (array_reverse($internalError->getTrace()) as $traceItem) {
if ($traceItem['file'] === null) {
continue;
}
$file = $fileHelper->normalizePath($traceItem['file'], '/');
if (str_contains($file, '/larastan/')) {
$hasLarastan = true;
$isLaravelLast = false;
continue;
}
if (!str_contains($file, '/laravel/framework/')) {
continue;
}
$isLaravelLast = true;
}
if ($hasLarastan) {
if ($isLaravelLast) {
$message .= "\n";
$message .= "\n" . 'This message is coming from Laravel Framework itself.';
$message .= "\n" . 'Larastan boots up your application in order to provide';
$message .= "\n" . 'smarter static analysis of your codebase.';
$message .= "\n";
$message .= "\n" . 'In order to do that, the environment you run PHPStan in';
$message .= "\n" . 'must match the environment you run your application in.';
$message .= "\n";
$message .= "\n" . 'Make sure you\'ve set your environment variables';
$message .= "\n" . 'or the .env file correctly.';
return $message;
}
$bugReportUrl = 'https://github.com/larastan/larastan/issues/new?template=bug-report.md';
} else {
$bugReportUrl = 'https://github.com/phpstan/phpstan/issues/new?template=Bug_report.yaml';
}
if ($internalError->getTraceAsString() !== null) {
if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
$firstTraceItem = $internalError->getTrace()[0] ?? null;
$trace = '';
if ($firstTraceItem !== null && $firstTraceItem['file'] !== null && $firstTraceItem['line'] !== null) {
$trace = sprintf('## %s(%d)%s', $firstTraceItem['file'], $firstTraceItem['line'], "\n");
}
$trace .= $internalError->getTraceAsString();
if ($internalError->shouldReportBug()) {
$message .= sprintf('%sPost the following stack trace to %s: %s%s', "\n", $bugReportUrl, "\n", $trace);
} else {
$message .= sprintf('%s%s', "\n\n", $trace);
}
} else {
if ($internalError->shouldReportBug()) {
$message .= sprintf('%sRun PHPStan with -v option and post the stack trace to:%s%s%s', "\n\n", "\n", $bugReportUrl, "\n");
} else {
$message .= sprintf('%sRun PHPStan with -v option to see the stack trace', "\n");
}
}
}
return $message;
}
private function generateBaseline(string $generateBaselineFile, InceptionResult $inceptionResult, AnalysisResult $analysisResult, OutputInterface $output, bool $allowEmptyBaseline, string $baselineExtension, bool $failWithoutResultCache, bool $onlyRemoveErrors, Container $container): int
{
$baselineFileDirectory = dirname($generateBaselineFile);
$baselinePathHelper = new ParentDirectoryRelativePathHelper($baselineFileDirectory);
if ($onlyRemoveErrors) {
$analysisResult = $this->filterAnalysisResultForExistingErrors($analysisResult, $generateBaselineFile, $inceptionResult, $container, $baselinePathHelper);
}
if (!$allowEmptyBaseline && !$analysisResult->hasErrors()) {
$inceptionResult->getStdOutput()->getStyle()->error('No errors were found during the analysis. Baseline could not be generated.');
$inceptionResult->getStdOutput()->writeLineFormatted('To allow generating empty baselines, pass <fg=cyan>--allow-empty-baseline</> option.');
return $inceptionResult->handleReturn(1, $analysisResult->getPeakMemoryUsageBytes(), $this->analysisStartTime);
}
$streamOutput = $this->createStreamOutput();
$errorConsoleStyle = new ErrorsConsoleStyle(new StringInput(''), $streamOutput);
$baselineOutput = new SymfonyOutput($streamOutput, new SymfonyStyle($errorConsoleStyle));
if ($baselineExtension === 'php') {
$baselineErrorFormatter = new BaselinePhpErrorFormatter($baselinePathHelper);
$baselineErrorFormatter->formatErrors($analysisResult, $baselineOutput);
} else {
$baselineErrorFormatter = new BaselineNeonErrorFormatter($baselinePathHelper);
$existingBaselineContent = is_file($generateBaselineFile) ? FileReader::read($generateBaselineFile) : '';
$baselineErrorFormatter->formatErrors($analysisResult, $baselineOutput, $existingBaselineContent);
}
$stream = $streamOutput->getStream();
rewind($stream);
$baselineContents = stream_get_contents($stream);
if ($baselineContents === false) {
throw new ShouldNotHappenException();
}
try {
DirectoryCreator::ensureDirectoryExists($baselineFileDirectory, 0644);
} catch (DirectoryCreatorException $e) {
$inceptionResult->getStdOutput()->writeLineFormatted($e->getMessage());
return $inceptionResult->handleReturn(1, $analysisResult->getPeakMemoryUsageBytes(), $this->analysisStartTime);
}
try {
FileWriter::write($generateBaselineFile, $baselineContents);
} catch (CouldNotWriteFileException $e) {
$inceptionResult->getStdOutput()->writeLineFormatted($e->getMessage());
return $inceptionResult->handleReturn(1, $analysisResult->getPeakMemoryUsageBytes(), $this->analysisStartTime);
}
$errorsCount = 0;
$unignorableCount = 0;
foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) {
if (!$fileSpecificError->canBeIgnored()) {
$unignorableCount++;
if ($output->isVeryVerbose()) {
$inceptionResult->getStdOutput()->writeLineFormatted('<error>Unignorable errors could not be added to the baseline:</error>');
$inceptionResult->getStdOutput()->writeLineFormatted($fileSpecificError->getMessage());
$inceptionResult->getStdOutput()->writeLineFormatted($fileSpecificError->getFile());
$inceptionResult->getStdOutput()->writeLineFormatted('');
}
continue;
}
$errorsCount++;
}
$message = sprintf('Baseline generated with %d %s.', $errorsCount, $errorsCount === 1 ? 'error' : 'errors');
if (
$unignorableCount === 0
&& count($analysisResult->getNotFileSpecificErrors()) === 0
) {
$inceptionResult->getStdOutput()->getStyle()->success($message);
} else {
if ($output->isVeryVerbose()) {
$inceptionResult->getStdOutput()->getStyle()->warning($message . "\nSome errors could not be put into baseline.");
} else {
$inceptionResult->getStdOutput()->getStyle()->warning($message . "\nSome errors could not be put into baseline. Re-run PHPStan with \"-vv\" and fix them.");
}
}
$exitCode = 0;
if ($failWithoutResultCache && !$analysisResult->isResultCacheUsed()) {
$exitCode = 2;
}
return $inceptionResult->handleReturn($exitCode, $analysisResult->getPeakMemoryUsageBytes(), $this->analysisStartTime);
}
private function filterAnalysisResultForExistingErrors(AnalysisResult $analysisResult, string $generateBaselineFile, InceptionResult $inceptionResult, Container $container, ParentDirectoryRelativePathHelper $baselinePathHelper): AnalysisResult
{
$currentAnalysisErrors = $analysisResult->getFileSpecificErrors();
$currentBaselinedErrors = $this->getCurrentBaselinedErrors($generateBaselineFile, $inceptionResult);
/** @var BaselineIgnoredErrorHelper $baselineIgnoredErrorsHelper */
$baselineIgnoredErrorsHelper = $container->getByType(BaselineIgnoredErrorHelper::class);
$nextBaselinedErrors = $baselineIgnoredErrorsHelper->removeUnusedIgnoredErrors($currentBaselinedErrors, $currentAnalysisErrors, $baselinePathHelper);
return new AnalysisResult(
$nextBaselinedErrors,
$analysisResult->getNotFileSpecificErrors(),
$analysisResult->getInternalErrorObjects(),
$analysisResult->getWarnings(),
$analysisResult->getCollectedData(),
$analysisResult->isDefaultLevelUsed(),
$analysisResult->getProjectConfigFile(),
$analysisResult->isResultCacheSaved(),
$analysisResult->getPeakMemoryUsageBytes(),
$analysisResult->isResultCacheUsed(),
$analysisResult->getChangedProjectExtensionFilesOutsideOfAnalysedPaths(),
);
}
/**
* @param string[] $files
*/
private function runFixer(InceptionResult $inceptionResult, Container $container, bool $onlyFiles, InputInterface $input, OutputInterface $output, array $files): int
{
$ciDetector = new CiDetector();
if ($ciDetector->isCiDetected()) {
$inceptionResult->getStdOutput()->writeLineFormatted('PHPStan Pro can\'t run in CI environment yet. Stay tuned!');
return $inceptionResult->handleReturn(1, null, $this->analysisStartTime);
}
/** @var FixerApplication $fixerApplication */
$fixerApplication = $container->getByType(FixerApplication::class);
return $fixerApplication->run(
$inceptionResult->getProjectConfigFile(),
$input,
$output,
count($files),
$_SERVER['argv'][0],
);
}
private function runDiagnoseExtensions(Container $container, Output $errorOutput): void
{
if (!$errorOutput->isDebug()) {
return;
}
/** @var PHPStanDiagnoseExtension $phpstanDiagnoseExtension */
$phpstanDiagnoseExtension = $container->getService('phpstanDiagnoseExtension');
// not using tag for this extension to make sure it's always first
$phpstanDiagnoseExtension->print($errorOutput);
/** @var DiagnoseExtension $extension */
foreach ($container->getServicesByTag(DiagnoseExtension::EXTENSION_TAG) as $extension) {
$extension->print($errorOutput);
}
}
/**
* @return mixed[][]
*/
private function getCurrentBaselinedErrors(string $generateBaselineFile, InceptionResult $inceptionResult): array
{
$loader = new Loader();
try {
$currentBaselineConfig = $loader->load($generateBaselineFile);
$baselinedErrors = $currentBaselineConfig['parameters']['ignoreErrors'] ?? [];
} catch (FileNotFoundException) {
// currently no baseline file -> empty config
$baselinedErrors = [];
} catch (InvalidStateException $invalidStateException) {
$inceptionResult->getErrorOutput()->writeLineFormatted($invalidStateException->getMessage());
throw $invalidStateException;
}
return $baselinedErrors;
}
}