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