-
Notifications
You must be signed in to change notification settings - Fork 18
/
Fixer.php
127 lines (101 loc) · 3.08 KB
/
Fixer.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
<?php
namespace Symfony\Upgrade;
use Symfony\CS\ErrorsManager;
use Symfony\CS\FixerInterface;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo as FinderSplFileInfo;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Upgrade\Fixer\Iterator\FixerIterator;
class Fixer
{
const VERSION = '0.1.3';
private $fixers = [];
private $finder;
private $errorsManager;
private $stopwatch;
public function __construct(
\Traversable $finder,
ErrorsManager $errorsManager = null,
Stopwatch $stopwatch = null
) {
$this->finder = $finder;
$this->errorsManager = $errorsManager;
$this->stopwatch = $stopwatch;
}
public function registerBuiltInFixers()
{
foreach (new FixerIterator() as $fixer) {
$this->addFixer($fixer);
}
}
public function addFixer(FixerInterface $fixer)
{
$this->fixers[] = $fixer;
}
public function getFixers()
{
return $this->fixers;
}
public function fix($dryRun = false)
{
$changed = [];
if ($this->stopwatch) {
$this->stopwatch->openSection();
}
foreach ($this->finder as $file) {
if ($file->isDir() || $file->isLink()) {
continue;
}
if ($this->stopwatch) {
$this->stopwatch->start($this->getFileRelativePathname($file));
}
if ($fixInfo = $this->fixFile($file, $dryRun)) {
$changed[$this->getFileRelativePathname($file)] = $fixInfo;
}
if ($this->stopwatch) {
$this->stopwatch->stop($this->getFileRelativePathname($file));
}
}
if ($this->stopwatch) {
$this->stopwatch->stopSection('fixFile');
}
return $changed;
}
private function fixFile(\SplFileInfo $file, $dryRun)
{
$new = $old = file_get_contents($file->getRealpath());
$appliedFixers = [];
Tokens::clearCache();
try {
foreach ($this->fixers as $fixer) {
if (!$fixer->supports($file)) {
continue;
}
$newest = $fixer->fix($file, $new);
if ($newest !== $new) {
$appliedFixers[] = $fixer->getName();
}
$new = $newest;
}
} catch (\Exception $e) {
if ($this->errorsManager) {
$this->errorsManager->report(ErrorsManager::ERROR_TYPE_EXCEPTION, $this->getFileRelativePathname($file), $e->__toString());
}
return;
}
if ($new !== $old) {
if (!$dryRun) {
file_put_contents($file->getRealpath(), $new);
}
}
return $appliedFixers;
}
private function getFileRelativePathname(\SplFileInfo $file)
{
if ($file instanceof FinderSplFileInfo) {
return $file->getRelativePathname();
}
return $file->getPathname();
}
}