-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
RandomApiMigrationFixer.php
170 lines (149 loc) · 6.17 KB
/
RandomApiMigrationFixer.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
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
<?php
declare(strict_types=1);
/*
* 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\Alias;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* @author Vladimir Reznichenko <kalessil@gmail.com>
*/
final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer implements ConfigurableFixerInterface
{
/**
* @var array
*/
private static $argumentCounts = [
'getrandmax' => [0],
'mt_rand' => [1, 2],
'rand' => [0, 2],
'srand' => [0, 1],
'random_int' => [0, 2],
];
/**
* {@inheritdoc}
*/
public function configure(array $configuration): void
{
parent::configure($configuration);
foreach ($this->configuration['replacements'] as $functionName => $replacement) {
$this->configuration['replacements'][$functionName] = [
'alternativeName' => $replacement,
'argumentCount' => self::$argumentCounts[$functionName],
];
}
}
/**
* {@inheritdoc}
*/
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replaces `rand`, `srand`, `getrandmax` functions calls with their `mt_*` analogs or `random_int`.',
[
new CodeSample("<?php\n\$a = getrandmax();\n\$a = rand(\$b, \$c);\n\$a = srand();\n"),
new CodeSample(
"<?php\n\$a = getrandmax();\n\$a = rand(\$b, \$c);\n\$a = srand();\n",
['replacements' => ['getrandmax' => 'mt_getrandmax']]
),
new CodeSample(
"<?php \$a = rand(\$b, \$c);\n",
['replacements' => ['rand' => 'random_int']]
),
],
null,
'Risky when the configured functions are overridden. Or when relying on the seed based generating of the numbers.'
);
}
/**
* {@inheritdoc}
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
foreach ($this->configuration['replacements'] as $functionIdentity => $functionReplacement) {
if ($functionIdentity === $functionReplacement['alternativeName']) {
continue;
}
$currIndex = 0;
do {
// try getting function reference and translate boundaries for humans
$boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1);
if (null === $boundaries) {
// next function search, as current one not found
continue 2;
}
[$functionName, $openParenthesis, $closeParenthesis] = $boundaries;
$count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis);
if (!\in_array($count, $functionReplacement['argumentCount'], true)) {
continue 2;
}
// analysing cursor shift, so nested calls could be processed
$currIndex = $openParenthesis;
$tokens[$functionName] = new Token([T_STRING, $functionReplacement['alternativeName']]);
if (0 === $count && 'random_int' === $functionReplacement['alternativeName']) {
$tokens->insertAt($currIndex + 1, [
new Token([T_LNUMBER, '0']),
new Token(','),
new Token([T_WHITESPACE, ' ']),
new Token([T_STRING, 'getrandmax']),
new Token('('),
new Token(')'),
]);
$currIndex += 6;
}
} while (null !== $currIndex);
}
}
/**
* {@inheritdoc}
*/
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('replacements', 'Mapping between replaced functions with the new ones.'))
->setAllowedTypes(['array'])
->setAllowedValues([static function (array $value): bool {
foreach ($value as $functionName => $replacement) {
if (!\array_key_exists($functionName, self::$argumentCounts)) {
throw new InvalidOptionsException(sprintf(
'Function "%s" is not handled by the fixer.',
$functionName
));
}
if (!\is_string($replacement)) {
throw new InvalidOptionsException(sprintf(
'Replacement for function "%s" must be a string, "%s" given.',
$functionName,
\is_object($replacement) ? \get_class($replacement) : \gettype($replacement)
));
}
}
return true;
}])
->setDefault([
'getrandmax' => 'mt_getrandmax',
'rand' => 'mt_rand', // @TODO change to `random_int` as default on 4.0
'srand' => 'mt_srand',
])
->getOption(),
]);
}
}