Last active
October 6, 2020 16:21
-
-
Save LeonardoCA/870b6dc52e3327d86d2fd15ddb2f797a to your computer and use it in GitHub Desktop.
PHPStan formatter grouping errors by error type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types = 1); | |
namespace App\PHPStan; | |
use PHPStan\Command\AnalysisResult; | |
use PHPStan\Command\ErrorFormatter\ErrorFormatter; | |
use Symfony\Component\Console\Style\OutputStyle; | |
class SummaryErrorFormatter implements ErrorFormatter | |
{ | |
public function formatErrors( | |
AnalysisResult $analysisResult, | |
OutputStyle $style | |
): int | |
{ | |
if (!$analysisResult->hasErrors()) { | |
return 0; | |
} | |
foreach ($analysisResult->getNotFileSpecificErrors() as $notFileSpecificError) { | |
$style->writeln(sprintf('?:?:%s', $notFileSpecificError)); | |
} | |
$errorsList=[]; | |
foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) { | |
// this regular expressions are suboptimal and not covering everything | |
//just a quick solution to test if such view is useful | |
$index = preg_replace( | |
'#[a-zA-Z_\:()\|]*\\\[a-zA-Z_\:()\]]*|\$[a-zA-Z_]*|offset [\d]*|[A-Z_]{5,}#', | |
'?', | |
$fileSpecificError->getMessage() | |
); | |
$index = preg_replace('#[a-zA-Z]*\([.]*\)#', '?', $index); | |
$index = preg_replace( | |
'/mixed|int|string|float|DateTime|array|bool|null|\#[0-9]+|\(.*\)|[^\s]*::__|[^\s]*::|\"[^\"]*\"/', | |
'?', | |
$index | |
); | |
$index = preg_replace('#[\?\|]+#', '?', $index); | |
$errorsList[$index][] = sprintf( | |
'%s:%d %s', | |
$fileSpecificError->getFile(), | |
$fileSpecificError->getLine() ?? '?', | |
$fileSpecificError->getMessage() | |
); | |
} | |
$errorTypesCount = count($errorsList); | |
foreach ($errorsList as $errorMsg => $filesList) { | |
$style->writeln(sprintf('%dx: %s',count($filesList) , $errorMsg)); | |
foreach ($filesList as $fileInfo) { | |
// comment out this line to have a compact list of error types | |
$style->writeln(sprintf(' - %s', $fileInfo)); | |
} | |
} | |
$style->note(sprintf($errorTypesCount === 1 ? 'Found %d error type' : 'Found %d error types', $errorTypesCount)); | |
$style->error(sprintf( | |
$analysisResult->getTotalErrorsCount() === 1 ? 'Found %d error' : 'Found %d errors', | |
$analysisResult->getTotalErrorsCount() | |
)); | |
return 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quick and dirty fix for recent versions of phpstan (I have 0.12.43):
use Symfony\Component\Console\Style\OutputStyle;
touse PHPStan\Command\Output;
$style->*()
to->writeLineFormatted()
See phpstan/phpstan#1686 for some background info about all this