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: * Applies the fixes of errors to the files on disk in one go, like one round of `phpstan analyse --fix`.
15: *
16: * The fix of an error is applied whole or not at all. It is skipped when it overlaps with a fix
17: * of an earlier error or when a file it changes was changed since the analysis.
18: * Fixing errors caused by other fixes needs a new analysis, which `phpstan analyse --fix` runs in rounds.
19: *
20: * @api
21: */
22: #[AutowiredService]
23: final class ErrorFixer
24: {
25:
26: public function __construct(private Patcher $patcher)
27: {
28: }
29:
30: /**
31: * Errors that are not fixable are ignored.
32: *
33: * @param list<Error> $errors
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: foreach ($error->getFixedErrorDiffs() as $diff) {
46: if (!$diff->isBuilt()) {
47: continue 2;
48: }
49: }
50:
51: $fixableErrors[] = $error;
52: $diffGroups[] = $error->getFixedErrorDiffs();
53: foreach ($error->getFixedErrorDiffs() as $diff) {
54: if (array_key_exists($diff->file, $contentsByFile) || !is_file($diff->file)) {
55: continue;
56: }
57:
58: $contentsByFile[$diff->file] = FileReader::read($diff->file);
59: }
60: }
61:
62: $result = $this->patcher->apply($contentsByFile, $diffGroups);
63:
64: $changedFiles = [];
65: foreach ($result['contents'] as $file => $contents) {
66: if ($contents === $contentsByFile[$file]) {
67: continue;
68: }
69:
70: FileWriter::write($file, $contents);
71: $changedFiles[] = $file;
72: }
73:
74: $skippedErrors = [];
75: foreach ($result['skippedGroups'] as $key) {
76: $skippedErrors[] = $fixableErrors[$key];
77: unset($fixableErrors[$key]);
78: }
79:
80: return new FixResult(array_values($fixableErrors), $skippedErrors, $changedFiles);
81: }
82:
83: }
84: