-
Notifications
You must be signed in to change notification settings - Fork 0
/
PrettierPHPFixer.php
106 lines (94 loc) · 2.26 KB
/
PrettierPHPFixer.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
<?php
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\Filesystem\Filesystem;
/**
* Fixer for using prettier-php to fix.
*/
final class PrettierPHPFixer implements FixerInterface
{
/**
* {@inheritdoc}
*/
public function getPriority()
{
// Allow prettier to pre-process the code before php-cs-fixer
return 999;
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens)
{
return true;
}
/**
* {@inheritdoc}
*/
public function isRisky()
{
return false;
}
/**
* {@inheritdoc}
*/
public function fix(SplFileInfo $file, Tokens $tokens)
{
if (
0 < $tokens->count() &&
$this->isCandidate($tokens) &&
$this->supports($file)
) {
$this->applyFix($file, $tokens);
}
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'Prettier/php';
}
/**
* {@inheritdoc}
*/
public function supports(SplFileInfo $file)
{
return true;
}
/**
* {@inheritdoc}
*/
private function applyFix(SplFileInfo $file, Tokens $tokens)
{
$tmpFile = $this->getTmpFile($file);
exec(
"yarn exec -- prettier --write --tab-width=4 --single-quote=true --trailing-comma-php=php7.3 $tmpFile"
);
$content = file_get_contents($tmpFile);
$tokens->setCode($content);
(new Filesystem())->remove($tmpFile);
}
/**
* Create a Temp file with the same content as given file.
*
* @param SplFileInfo $file file to be copied
*
* @return string tmp file name
*/
private function getTmpFile(SplFileInfo $file): string
{
$fileSys = new Filesystem();
$tmpFolderPath = __DIR__ . DIRECTORY_SEPARATOR . 'tmp';
$fileSys->mkdir($tmpFolderPath);
$tmpFileName = str_replace(
array(DIRECTORY_SEPARATOR, ':'),
'_',
$file->getRealPath()
);
$tmpFilePath =
$tmpFolderPath . DIRECTORY_SEPARATOR . '__' . $tmpFileName;
$fileSys->copy($file->getRealPath(), $tmpFilePath, true);
return $tmpFilePath;
}
}