| 1: | <?php declare(strict_types = 1); |
| 2: | |
| 3: | namespace PHPStan\Command\ErrorFormatter; |
| 4: | |
| 5: | use PHPStan\Analyser\Error; |
| 6: | use PHPStan\Command\AnalyseCommand; |
| 7: | use PHPStan\Command\AnalysisResult; |
| 8: | use PHPStan\Command\CommandHelper; |
| 9: | use PHPStan\Command\Output; |
| 10: | use PHPStan\DependencyInjection\AutowiredParameter; |
| 11: | use PHPStan\DependencyInjection\AutowiredService; |
| 12: | use PHPStan\File\RelativePathHelper; |
| 13: | use PHPStan\File\SimpleRelativePathHelper; |
| 14: | use Symfony\Component\Console\Formatter\OutputFormatter; |
| 15: | use function array_map; |
| 16: | use function array_slice; |
| 17: | use function count; |
| 18: | use function explode; |
| 19: | use function getenv; |
| 20: | use function implode; |
| 21: | use function in_array; |
| 22: | use function is_string; |
| 23: | use function ltrim; |
| 24: | use function rtrim; |
| 25: | use function sprintf; |
| 26: | use function str_contains; |
| 27: | use function str_replace; |
| 28: | |
| 29: | #[AutowiredService(name: 'errorFormatter.table')] |
| 30: | final class TableErrorFormatter implements ErrorFormatter |
| 31: | { |
| 32: | |
| 33: | public const ERRORS_LIMIT = 1000; |
| 34: | private const FORCE_SHOW_ALL_ERRORS = 'PHPSTAN_TABLE_ERROR_FORMATTER_FORCE_SHOW_ALL_ERRORS'; |
| 35: | |
| 36: | public function __construct( |
| 37: | private RelativePathHelper $relativePathHelper, |
| 38: | #[AutowiredParameter(ref: '@simpleRelativePathHelper')] |
| 39: | private SimpleRelativePathHelper $simpleRelativePathHelper, |
| 40: | private CiDetectedErrorFormatter $ciDetectedErrorFormatter, |
| 41: | #[AutowiredParameter(ref: '%tipsOfTheDay%')] |
| 42: | private bool $showTipsOfTheDay, |
| 43: | #[AutowiredParameter] |
| 44: | private ?string $editorUrl, |
| 45: | #[AutowiredParameter] |
| 46: | private ?string $editorUrlTitle, |
| 47: | #[AutowiredParameter] |
| 48: | private string $usedLevel, |
| 49: | private ?int $errorsBudget = null, |
| 50: | ) |
| 51: | { |
| 52: | if ($this->errorsBudget !== null) { |
| 53: | return; |
| 54: | } |
| 55: | |
| 56: | $forceShowAll = getenv(self::FORCE_SHOW_ALL_ERRORS); |
| 57: | if (!in_array($forceShowAll, [false, '0'], true)) { |
| 58: | return; |
| 59: | } |
| 60: | |
| 61: | $this->errorsBudget = self::ERRORS_LIMIT; |
| 62: | } |
| 63: | |
| 64: | |
| 65: | public function formatErrors( |
| 66: | AnalysisResult $analysisResult, |
| 67: | Output $output, |
| 68: | ): int |
| 69: | { |
| 70: | $this->ciDetectedErrorFormatter->formatErrors($analysisResult, $output); |
| 71: | $projectConfigFile = 'phpstan.neon'; |
| 72: | if ($analysisResult->getProjectConfigFile() !== null) { |
| 73: | $projectConfigFile = $this->relativePathHelper->getRelativePath($analysisResult->getProjectConfigFile()); |
| 74: | } |
| 75: | |
| 76: | $style = $output->getStyle(); |
| 77: | |
| 78: | if (!$analysisResult->hasErrors() && !$analysisResult->hasWarnings()) { |
| 79: | $style->success('No errors'); |
| 80: | $this->printFixableIgnoredErrors($analysisResult, $output); |
| 81: | |
| 82: | if ($this->showTipsOfTheDay) { |
| 83: | if ($analysisResult->isDefaultLevelUsed()) { |
| 84: | $output->writeLineFormatted('š” Tip of the Day:'); |
| 85: | $output->writeLineFormatted(sprintf( |
| 86: | "PHPStan is performing only the most basic checks.\nYou can pass a higher rule level through the <fg=cyan>--%s</> option\n(the default and current level is %d) to analyse code more thoroughly.", |
| 87: | AnalyseCommand::OPTION_LEVEL, |
| 88: | (int) AnalyseCommand::DEFAULT_LEVEL, |
| 89: | )); |
| 90: | $output->writeLineFormatted(''); |
| 91: | } |
| 92: | } |
| 93: | |
| 94: | return 0; |
| 95: | } |
| 96: | |
| 97: | |
| 98: | $fileErrors = []; |
| 99: | $fixableErrorsCount = 0; |
| 100: | foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) { |
| 101: | if ($fileSpecificError->getFixedErrorDiffs() !== []) { |
| 102: | $fixableErrorsCount++; |
| 103: | } |
| 104: | if (!isset($fileErrors[$fileSpecificError->getFile()])) { |
| 105: | $fileErrors[$fileSpecificError->getFile()] = []; |
| 106: | } |
| 107: | |
| 108: | $fileErrors[$fileSpecificError->getFile()][] = $fileSpecificError; |
| 109: | } |
| 110: | |
| 111: | $errorsBudget = $this->errorsBudget; |
| 112: | $printedErrors = 0; |
| 113: | foreach ($fileErrors as $file => $errors) { |
| 114: | $rows = []; |
| 115: | foreach ($errors as $error) { |
| 116: | $message = $error->getMessage(); |
| 117: | $filePath = $error->getTraitFilePath() ?? $error->getFilePath(); |
| 118: | if ( |
| 119: | $error->getIdentifier() !== null |
| 120: | && in_array($error->getIdentifier(), ['phpstan.type', 'phpstan.nativeType', 'phpstan.variable', 'phpstan.dumpType', 'phpstan.unknownExpectation'], true) |
| 121: | ) { |
| 122: | $message = '<fg=red>' . OutputFormatter::escape($message) . '</>'; |
| 123: | } |
| 124: | if ($error->getFixedErrorDiffs() !== []) { |
| 125: | $message .= ' š§'; |
| 126: | } |
| 127: | if ($error->getIdentifier() !== null) { |
| 128: | $message .= "\n"; |
| 129: | $message .= 'šŖŖ ' . $error->getIdentifier(); |
| 130: | if (!$error->canBeIgnored()) { |
| 131: | $message .= ' <fg=red>(non-ignorable)</>'; |
| 132: | } |
| 133: | } |
| 134: | if ($error->getTip() !== null) { |
| 135: | $tip = $error->getTip(); |
| 136: | $tip = str_replace('%configurationFile%', $projectConfigFile, $tip); |
| 137: | |
| 138: | $message .= "\n"; |
| 139: | if (str_contains($tip, "\n")) { |
| 140: | $lines = explode("\n", $tip); |
| 141: | foreach ($lines as $line) { |
| 142: | $message .= 'š” ' . ltrim($line, ' ā¢') . "\n"; |
| 143: | } |
| 144: | $message = rtrim($message, "\n"); |
| 145: | } else { |
| 146: | $message .= 'š” ' . $tip; |
| 147: | } |
| 148: | } |
| 149: | |
| 150: | if (getenv('TERMINAL_EMULATOR') === 'JetBrains-JediTerm') { |
| 151: | $title = $this->simpleRelativePathHelper->getRelativePath($filePath); |
| 152: | $message .= sprintf("\nat %s:%d", $title, $error->getLine() ?? 0); |
| 153: | |
| 154: | } elseif (is_string($this->editorUrl)) { |
| 155: | $url = str_replace( |
| 156: | ['%file%', '%relFile%', '%line%'], |
| 157: | [$filePath, $this->simpleRelativePathHelper->getRelativePath($filePath), (string) $error->getLine()], |
| 158: | $this->editorUrl, |
| 159: | ); |
| 160: | |
| 161: | if (is_string($this->editorUrlTitle)) { |
| 162: | $title = str_replace( |
| 163: | ['%file%', '%relFile%', '%line%'], |
| 164: | [$filePath, $this->simpleRelativePathHelper->getRelativePath($filePath), (string) $error->getLine()], |
| 165: | $this->editorUrlTitle, |
| 166: | ); |
| 167: | } else { |
| 168: | $title = $this->relativePathHelper->getRelativePath($filePath); |
| 169: | } |
| 170: | |
| 171: | $message .= "\nāļø <href=" . OutputFormatter::escape($url) . '>' . $title . '</>'; |
| 172: | } |
| 173: | |
| 174: | $rows[] = [ |
| 175: | $this->formatLineNumber($error->getLine()), |
| 176: | $message, |
| 177: | ]; |
| 178: | } |
| 179: | |
| 180: | $printedErrors += count($rows); |
| 181: | if ($errorsBudget !== null && $printedErrors > $errorsBudget) { |
| 182: | $rows = array_slice($rows, 0, $errorsBudget - ($printedErrors - count($rows))); |
| 183: | |
| 184: | $style->table(['Line', $this->relativePathHelper->getRelativePath($file)], $rows); |
| 185: | break; |
| 186: | } |
| 187: | |
| 188: | $style->table(['Line', $this->relativePathHelper->getRelativePath($file)], $rows); |
| 189: | } |
| 190: | |
| 191: | if (count($analysisResult->getNotFileSpecificErrors()) > 0) { |
| 192: | $style->table(['', 'Error'], array_map(static fn (string $error): array => ['', OutputFormatter::escape($error)], $analysisResult->getNotFileSpecificErrors())); |
| 193: | } |
| 194: | |
| 195: | $warningsCount = count($analysisResult->getWarnings()); |
| 196: | if ($warningsCount > 0) { |
| 197: | $style->table(['', 'Warning'], array_map(static fn (string $warning): array => ['', OutputFormatter::escape($warning)], $analysisResult->getWarnings())); |
| 198: | } |
| 199: | |
| 200: | if ($errorsBudget !== null && $printedErrors > $errorsBudget) { |
| 201: | $style->error(sprintf('Found %s+ errors', $errorsBudget)); |
| 202: | |
| 203: | $note = []; |
| 204: | $note[] = sprintf('Result is limited to the first %d errors', $errorsBudget); |
| 205: | if ($this->usedLevel !== CommandHelper::DEFAULT_LEVEL) { |
| 206: | $note[] = '- Consider lowering the PHPStan level'; |
| 207: | } |
| 208: | $note[] = sprintf('- Pass %s=1 environment variable to show all errors', self::FORCE_SHOW_ALL_ERRORS); |
| 209: | $note[] = '- Consider using PHPStan Pro for more comfortable error browsing'; |
| 210: | $note[] = ' Learn more: https://phpstan.com'; |
| 211: | $style->note(implode("\n", $note)); |
| 212: | } else { |
| 213: | $finalMessage = sprintf($analysisResult->getTotalErrorsCount() === 1 ? 'Found %d error' : 'Found %d errors', $analysisResult->getTotalErrorsCount()); |
| 214: | if ($warningsCount > 0) { |
| 215: | $finalMessage .= sprintf($warningsCount === 1 ? ' and %d warning' : ' and %d warnings', $warningsCount); |
| 216: | } |
| 217: | |
| 218: | if ($analysisResult->getTotalErrorsCount() > 0) { |
| 219: | $style->error($finalMessage); |
| 220: | } else { |
| 221: | $style->warning($finalMessage); |
| 222: | } |
| 223: | } |
| 224: | |
| 225: | if ($fixableErrorsCount > 0) { |
| 226: | $output->writeLineFormatted(sprintf('š§ %d %s can be fixed automatically. Run PHPStan again with <fg=cyan>--fix</>.', $fixableErrorsCount, $fixableErrorsCount === 1 ? 'error' : 'errors')); |
| 227: | if (count($analysisResult->getFixableIgnoredErrors()) === 0) { |
| 228: | $output->writeLineFormatted(''); |
| 229: | } |
| 230: | } |
| 231: | $this->printFixableIgnoredErrors($analysisResult, $output); |
| 232: | |
| 233: | return $analysisResult->getTotalErrorsCount() > 0 ? 1 : 0; |
| 234: | } |
| 235: | |
| 236: | private function printFixableIgnoredErrors(AnalysisResult $analysisResult, Output $output): void |
| 237: | { |
| 238: | $count = count($analysisResult->getFixableIgnoredErrors()); |
| 239: | if ($count === 0) { |
| 240: | return; |
| 241: | } |
| 242: | |
| 243: | $output->writeLineFormatted(sprintf('<fg=gray>š§ %d ignored %s can be fixed automatically. Run PHPStan again with --fix-ignored.</>', $count, $count === 1 ? 'error' : 'errors')); |
| 244: | $output->writeLineFormatted(''); |
| 245: | } |
| 246: | |
| 247: | private function formatLineNumber(?int $lineNumber): string |
| 248: | { |
| 249: | if ($lineNumber === null) { |
| 250: | return ''; |
| 251: | } |
| 252: | |
| 253: | $isRunningInVSCodeTerminal = getenv('TERM_PROGRAM') === 'vscode'; |
| 254: | if ($isRunningInVSCodeTerminal) { |
| 255: | return ':' . $lineNumber; |
| 256: | } |
| 257: | |
| 258: | return (string) $lineNumber; |
| 259: | } |
| 260: | |
| 261: | } |
| 262: | |