RandomApiMigrationFixer.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Fixer\Alias;
  13. use PhpCsFixer\AbstractFunctionReferenceFixer;
  14. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  15. use PhpCsFixer\Fixer\ConfigurableFixerTrait;
  16. use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
  17. use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
  18. use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
  19. use PhpCsFixer\FixerDefinition\CodeSample;
  20. use PhpCsFixer\FixerDefinition\FixerDefinition;
  21. use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
  22. use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
  23. use PhpCsFixer\Tokenizer\Token;
  24. use PhpCsFixer\Tokenizer\Tokens;
  25. use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
  26. /**
  27. * @author Vladimir Reznichenko <kalessil@gmail.com>
  28. *
  29. * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
  30. *
  31. * @phpstan-type _AutogeneratedInputConfiguration array{
  32. * replacements?: array<string, string>
  33. * }
  34. * @phpstan-type _AutogeneratedComputedConfiguration array{
  35. * replacements: array<string, string>
  36. * }
  37. */
  38. final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer implements ConfigurableFixerInterface
  39. {
  40. /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
  41. use ConfigurableFixerTrait;
  42. /**
  43. * @var array<string, array<int, int>>
  44. */
  45. private static array $argumentCounts = [
  46. 'getrandmax' => [0],
  47. 'mt_rand' => [1, 2],
  48. 'rand' => [0, 2],
  49. 'srand' => [0, 1],
  50. 'random_int' => [0, 2],
  51. ];
  52. public function getDefinition(): FixerDefinitionInterface
  53. {
  54. return new FixerDefinition(
  55. 'Replaces `rand`, `srand`, `getrandmax` functions calls with their `mt_*` analogs or `random_int`.',
  56. [
  57. new CodeSample("<?php\n\$a = getrandmax();\n\$a = rand(\$b, \$c);\n\$a = srand();\n"),
  58. new CodeSample(
  59. "<?php\n\$a = getrandmax();\n\$a = rand(\$b, \$c);\n\$a = srand();\n",
  60. ['replacements' => ['getrandmax' => 'mt_getrandmax']]
  61. ),
  62. new CodeSample(
  63. "<?php \$a = rand(\$b, \$c);\n",
  64. ['replacements' => ['rand' => 'random_int']]
  65. ),
  66. ],
  67. null,
  68. 'Risky when the configured functions are overridden. Or when relying on the seed based generating of the numbers.'
  69. );
  70. }
  71. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  72. {
  73. $argumentsAnalyzer = new ArgumentsAnalyzer();
  74. foreach ($this->configuration['replacements'] as $functionIdentity => $functionReplacement) {
  75. if ($functionIdentity === $functionReplacement) {
  76. continue;
  77. }
  78. $currIndex = 0;
  79. do {
  80. // try getting function reference and translate boundaries for humans
  81. $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1);
  82. if (null === $boundaries) {
  83. // next function search, as current one not found
  84. continue 2;
  85. }
  86. [$functionName, $openParenthesis, $closeParenthesis] = $boundaries;
  87. $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis);
  88. if (!\in_array($count, self::$argumentCounts[$functionIdentity], true)) {
  89. continue 2;
  90. }
  91. // analysing cursor shift, so nested calls could be processed
  92. $currIndex = $openParenthesis;
  93. $tokens[$functionName] = new Token([T_STRING, $functionReplacement]);
  94. if (0 === $count && 'random_int' === $functionReplacement) {
  95. $tokens->insertAt($currIndex + 1, [
  96. new Token([T_LNUMBER, '0']),
  97. new Token(','),
  98. new Token([T_WHITESPACE, ' ']),
  99. new Token([T_STRING, 'getrandmax']),
  100. new Token('('),
  101. new Token(')'),
  102. ]);
  103. $currIndex += 6;
  104. }
  105. } while (null !== $currIndex);
  106. }
  107. }
  108. protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
  109. {
  110. return new FixerConfigurationResolver([
  111. (new FixerOptionBuilder('replacements', 'Mapping between replaced functions with the new ones.'))
  112. ->setAllowedTypes(['array<string, string>'])
  113. ->setAllowedValues([static function (array $value): bool {
  114. foreach ($value as $functionName => $replacement) {
  115. if (!\array_key_exists($functionName, self::$argumentCounts)) {
  116. throw new InvalidOptionsException(\sprintf(
  117. 'Function "%s" is not handled by the fixer.',
  118. $functionName
  119. ));
  120. }
  121. }
  122. return true;
  123. }])
  124. ->setDefault([
  125. 'getrandmax' => 'mt_getrandmax',
  126. 'rand' => 'mt_rand', // @TODO change to `random_int` as default on 4.0
  127. 'srand' => 'mt_srand',
  128. ])
  129. ->getOption(),
  130. ]);
  131. }
  132. }