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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author SpacePossum
*/
final class FunctionToConstantFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
/**
* @var string[]
*/
private static $availableFunctions;
/**
* @var array<string, Token>
*/
private $functionsFixMap;
public function __construct()
{
if (null === self::$availableFunctions) {
self::$availableFunctions = [
'get_called_class' => [
new Token([T_STATIC, 'static']),
new Token([T_DOUBLE_COLON, '::']),
new Token([CT::T_CLASS_CONSTANT, 'class']),
],
'get_class' => [new Token([T_CLASS_C, '__CLASS__'])],
'php_sapi_name' => [new Token([T_STRING, 'PHP_SAPI'])],
'phpversion' => [new Token([T_STRING, 'PHP_VERSION'])],
'pi' => [new Token([T_STRING, 'M_PI'])],
];
}
parent::__construct();
}
/**
* {@inheritdoc}
*/
public function configure(array $configuration = null)
{
parent::configure($configuration);
$this->functionsFixMap = [];
foreach ($this->configuration['functions'] as $key) {
$this->functionsFixMap[$key] = self::$availableFunctions[$key];
}
}
/**
* {@inheritdoc}
*/
public function getDefinition()
{
return new FixerDefinition(
'Replace core functions calls returning constants with the constants.',
[
new CodeSample("<?php\necho phpversion();\necho pi();\necho php_sapi_name();\n"),
new CodeSample("<?php\necho phpversion();\necho pi();\n", ['functions' => ['phpversion']]),
],
null,
'Risky when any of the configured functions to replace are overridden.'
);
}
/**
* {@inheritdoc}
*/
public function getPriority()
{
// should run before NativeFunctionCasingFixer
// must run before NoExtraBlankLinesFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, NoTrailingWhitespaceFixer and NoWhitespaceInBlankLineFixer
// must run after NoSpacesAfterFunctionNameFixer and NoSpacesInsideParenthesisFixer
return 1;
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_STRING);
}
/**
* {@inheritdoc}
*/
public function isRisky()
{
return true;
}
/**
* {@inheritdoc}
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
for ($index = $tokens->count() - 4; $index > 0; --$index) {
$candidate = $this->getReplaceCandidate($tokens, $index);
if (null === $candidate) {
continue;
}
$this->fixFunctionCallToConstant(
$tokens,
$index,
$candidate[0], // brace open
$candidate[1], // brace close
$candidate[2] // replacement
);
}
}
/**
* {@inheritdoc}
*/
protected function createConfigurationDefinition()
{
$functionNames = array_keys(self::$availableFunctions);
return new FixerConfigurationResolver([
(new FixerOptionBuilder('functions', 'List of function names to fix.'))
->setAllowedTypes(['array'])
->setAllowedValues([new AllowedValueSubset($functionNames)])
->setDefault([
'get_class',
'php_sapi_name',
'phpversion',
'pi',
// TODO on v3.0 add 'get_called_class' here
])
->getOption(),
]);
}
/**
* @param Tokens $tokens
* @param int $index
* @param int $braceOpenIndex
* @param int $braceCloseIndex
* @param Token[] $replacements
*/
private function fixFunctionCallToConstant(Tokens $tokens, $index, $braceOpenIndex, $braceCloseIndex, array $replacements)
{
$tokens->clearTokenAndMergeSurroundingWhitespace($braceCloseIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($braceOpenIndex);
if ($replacements[0]->isGivenKind([T_CLASS_C, T_STATIC])) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
if ($prevToken->isGivenKind(T_NS_SEPARATOR)) {
$tokens->clearAt($prevIndex);
}
}
$tokens->clearAt($index);
$tokens->insertAt($index, $replacements);
}
/**
* @param Tokens $tokens
* @param int $index
*
* @return null|array
*/
private function getReplaceCandidate(Tokens $tokens, $index)
{
// test if we are at a function all
if (!$tokens[$index]->isGivenKind(T_STRING)) {
return null;
}
$braceOpenIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$braceOpenIndex]->equals('(')) {
return null;
}
// test if function call without parameters
$braceCloseIndex = $tokens->getNextMeaningfulToken($braceOpenIndex);
if (!$tokens[$braceCloseIndex]->equals(')')) {
return null;
}
$functionNamePrefix = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$functionNamePrefix]->isGivenKind([T_DOUBLE_COLON, T_NEW, T_OBJECT_OPERATOR, T_FUNCTION, CT::T_RETURN_REF])) {
return null;
}
if ($tokens[$functionNamePrefix]->isGivenKind(T_NS_SEPARATOR)) {
// skip if the call is to a constructor or to a function in a namespace other than the default
$prevIndex = $tokens->getPrevMeaningfulToken($functionNamePrefix);
if ($tokens[$prevIndex]->isGivenKind([T_STRING, T_NEW])) {
return null;
}
}
// test if the function call is to a native PHP function
$lowerContent = strtolower($tokens[$index]->getContent());
if (!array_key_exists($lowerContent, $this->functionsFixMap)) {
return null;
}
$clones = [];
foreach ($this->functionsFixMap[$lowerContent] as $token) {
$clones[] = clone $token;
}
return [
$braceOpenIndex,
$braceCloseIndex,
$clones,
];
}
}