| 1: | <?php declare(strict_types = 1); |
| 2: | |
| 3: | namespace PHPStan\Fixable; |
| 4: | |
| 5: | use PHPStan\Analyser\Error; |
| 6: | use PHPStan\DependencyInjection\AutowiredService; |
| 7: | use PHPStan\File\FileReader; |
| 8: | use PHPStan\File\FileWriter; |
| 9: | use function array_key_exists; |
| 10: | use function array_values; |
| 11: | use function is_file; |
| 12: | |
| 13: | |
| 14: | |
| 15: | |
| 16: | |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | #[AutowiredService] |
| 23: | final class ErrorFixer |
| 24: | { |
| 25: | |
| 26: | public function __construct(private Patcher $patcher) |
| 27: | { |
| 28: | } |
| 29: | |
| 30: | |
| 31: | |
| 32: | |
| 33: | |
| 34: | |
| 35: | public function fix(array $errors): FixResult |
| 36: | { |
| 37: | $fixableErrors = []; |
| 38: | $diffGroups = []; |
| 39: | $contentsByFile = []; |
| 40: | foreach ($errors as $error) { |
| 41: | if (!$error->isFixable()) { |
| 42: | continue; |
| 43: | } |
| 44: | |
| 45: | $fixableErrors[] = $error; |
| 46: | $diffGroups[] = $error->getFixedErrorDiffs(); |
| 47: | foreach ($error->getFixedErrorDiffs() as $diff) { |
| 48: | if (array_key_exists($diff->file, $contentsByFile) || !is_file($diff->file)) { |
| 49: | continue; |
| 50: | } |
| 51: | |
| 52: | $contentsByFile[$diff->file] = FileReader::read($diff->file); |
| 53: | } |
| 54: | } |
| 55: | |
| 56: | $result = $this->patcher->apply($contentsByFile, $diffGroups); |
| 57: | |
| 58: | $changedFiles = []; |
| 59: | foreach ($result['contents'] as $file => $contents) { |
| 60: | if ($contents === $contentsByFile[$file]) { |
| 61: | continue; |
| 62: | } |
| 63: | |
| 64: | FileWriter::write($file, $contents); |
| 65: | $changedFiles[] = $file; |
| 66: | } |
| 67: | |
| 68: | $skippedErrors = []; |
| 69: | foreach ($result['skippedGroups'] as $key) { |
| 70: | $skippedErrors[] = $fixableErrors[$key]; |
| 71: | unset($fixableErrors[$key]); |
| 72: | } |
| 73: | |
| 74: | return new FixResult(array_values($fixableErrors), $skippedErrors, $changedFiles); |
| 75: | } |
| 76: | |
| 77: | } |
| 78: | |