Browse Source

RandomApiMigrationFixer - better docs and checks for "random_int"

SpacePossum 3 years ago
parent
commit
1dd11d3080

+ 1 - 0
.php_cs.dist

@@ -26,6 +26,7 @@ $finder = PhpCsFixer\Finder::create()
     ->append([
     ->append([
         __DIR__.'/dev-tools/doc.php',
         __DIR__.'/dev-tools/doc.php',
         __DIR__.'/php-cs-fixer',
         __DIR__.'/php-cs-fixer',
+        __FILE__,
     ])
     ])
 ;
 ;
 
 

+ 3 - 2
doc/rules/alias/random_api_migration.rst

@@ -3,11 +3,12 @@ Rule ``random_api_migration``
 =============================
 =============================
 
 
 Replaces ``rand``, ``srand``, ``getrandmax`` functions calls with their ``mt_*``
 Replaces ``rand``, ``srand``, ``getrandmax`` functions calls with their ``mt_*``
-analogs.
+analogs or ``random_int``.
 
 
 .. warning:: Using this rule is risky.
 .. warning:: Using this rule is risky.
 
 
-   Risky when the configured functions are overridden.
+   Risky when the configured functions are overridden. Or when relying on the
+   seed based generating of the numbers.
 
 
 Configuration
 Configuration
 -------------
 -------------

+ 1 - 1
doc/rules/index.rst

@@ -22,7 +22,7 @@ Alias
 - `pow_to_exponentiation <./alias/pow_to_exponentiation.rst>`_ *(risky)*
 - `pow_to_exponentiation <./alias/pow_to_exponentiation.rst>`_ *(risky)*
     Converts ``pow`` to the ``**`` operator.
     Converts ``pow`` to the ``**`` operator.
 - `random_api_migration <./alias/random_api_migration.rst>`_ *(risky)*
 - `random_api_migration <./alias/random_api_migration.rst>`_ *(risky)*
-    Replaces ``rand``, ``srand``, ``getrandmax`` functions calls with their ``mt_*`` analogs.
+    Replaces ``rand``, ``srand``, ``getrandmax`` functions calls with their ``mt_*`` analogs or ``random_int``.
 - `set_type_to_cast <./alias/set_type_to_cast.rst>`_ *(risky)*
 - `set_type_to_cast <./alias/set_type_to_cast.rst>`_ *(risky)*
     Cast shall be used, not ``settype``.
     Cast shall be used, not ``settype``.
 
 

+ 7 - 4
src/Fixer/Alias/RandomApiMigrationFixer.php

@@ -36,6 +36,7 @@ final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer imple
         'mt_rand' => [1, 2],
         'mt_rand' => [1, 2],
         'rand' => [0, 2],
         'rand' => [0, 2],
         'srand' => [0, 1],
         'srand' => [0, 1],
+        'random_int' => [0, 2],
     ];
     ];
 
 
     /**
     /**
@@ -59,7 +60,7 @@ final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer imple
     public function getDefinition()
     public function getDefinition()
     {
     {
         return new FixerDefinition(
         return new FixerDefinition(
-            'Replaces `rand`, `srand`, `getrandmax` functions calls with their `mt_*` analogs.',
+            '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"),
                 new CodeSample(
                 new CodeSample(
@@ -72,7 +73,7 @@ final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer imple
                 ),
                 ),
             ],
             ],
             null,
             null,
-            'Risky when the configured functions are overridden.'
+            'Risky when the configured functions are overridden. Or when relying on the seed based generating of the numbers.'
         );
         );
     }
     }
 
 
@@ -97,9 +98,11 @@ final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer imple
             }
             }
 
 
             $currIndex = 0;
             $currIndex = 0;
+
             while (null !== $currIndex) {
             while (null !== $currIndex) {
                 // try getting function reference and translate boundaries for humans
                 // try getting function reference and translate boundaries for humans
                 $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1);
                 $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1);
+
                 if (null === $boundaries) {
                 if (null === $boundaries) {
                     // next function search, as current one not found
                     // next function search, as current one not found
                     continue 2;
                     continue 2;
@@ -107,13 +110,13 @@ final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer imple
 
 
                 list($functionName, $openParenthesis, $closeParenthesis) = $boundaries;
                 list($functionName, $openParenthesis, $closeParenthesis) = $boundaries;
                 $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis);
                 $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis);
+
                 if (!\in_array($count, $functionReplacement['argumentCount'], true)) {
                 if (!\in_array($count, $functionReplacement['argumentCount'], true)) {
                     continue 2;
                     continue 2;
                 }
                 }
 
 
                 // analysing cursor shift, so nested calls could be processed
                 // analysing cursor shift, so nested calls could be processed
                 $currIndex = $openParenthesis;
                 $currIndex = $openParenthesis;
-
                 $tokens[$functionName] = new Token([T_STRING, $functionReplacement['alternativeName']]);
                 $tokens[$functionName] = new Token([T_STRING, $functionReplacement['alternativeName']]);
 
 
                 if (0 === $count && 'random_int' === $functionReplacement['alternativeName']) {
                 if (0 === $count && 'random_int' === $functionReplacement['alternativeName']) {
@@ -162,7 +165,7 @@ final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer imple
                 }])
                 }])
                 ->setDefault([
                 ->setDefault([
                     'getrandmax' => 'mt_getrandmax',
                     'getrandmax' => 'mt_getrandmax',
-                    'rand' => 'mt_rand',
+                    'rand' => 'mt_rand', // @TODO change to `random_int` as default on 4.0
                     'srand' => 'mt_srand',
                     'srand' => 'mt_srand',
                 ])
                 ])
                 ->getOption(),
                 ->getOption(),

+ 1 - 0
src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php

@@ -269,6 +269,7 @@ class Sample
         }
         }
 
 
         $functionIndex = $tokens->getTokenNotOfKindsSibling($nextNotWhite - 1, 1, [T_ABSTRACT, T_FINAL, T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_WHITESPACE, T_COMMENT, T_DOC_COMMENT]);
         $functionIndex = $tokens->getTokenNotOfKindsSibling($nextNotWhite - 1, 1, [T_ABSTRACT, T_FINAL, T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_WHITESPACE, T_COMMENT, T_DOC_COMMENT]);
+
         if ($tokens[$functionIndex]->isGivenKind(T_FUNCTION)) {
         if ($tokens[$functionIndex]->isGivenKind(T_FUNCTION)) {
             $this->correctLineBreaks($tokens, $elementEndIndex, $nextNotWhite, 2);
             $this->correctLineBreaks($tokens, $elementEndIndex, $nextNotWhite, 2);
 
 

+ 1 - 1
src/RuleSet/RuleSet.php

@@ -49,7 +49,7 @@ class RuleSet implements RuleSetInterface
                 throw new \InvalidArgumentException(sprintf('Missing value for "%s" rule/set.', $value));
                 throw new \InvalidArgumentException(sprintf('Missing value for "%s" rule/set.', $value));
             }
             }
 
 
-            if (true !== $value && false !== $value && !\is_array($value)) {
+            if (!\is_bool($value) && !\is_array($value)) {
                 // @TODO drop me on 3.0
                 // @TODO drop me on 3.0
                 if (null === $value) {
                 if (null === $value) {
                     Utils::triggerDeprecation(new InvalidFixerConfigurationException(
                     Utils::triggerDeprecation(new InvalidFixerConfigurationException(

+ 5 - 2
src/Tokenizer/Analyzer/FunctionsAnalyzer.php

@@ -194,15 +194,18 @@ final class FunctionsAnalyzer
         }
         }
 
 
         $operatorIndex = $tokens->getPrevMeaningfulToken($index);
         $operatorIndex = $tokens->getPrevMeaningfulToken($index);
-        if (!$tokens->offsetExists($operatorIndex)) {
+
+        if (null === $operatorIndex) {
             return false;
             return false;
         }
         }
+
         if (!$tokens[$operatorIndex]->isObjectOperator() && !$tokens[$operatorIndex]->isGivenKind(T_DOUBLE_COLON)) {
         if (!$tokens[$operatorIndex]->isObjectOperator() && !$tokens[$operatorIndex]->isGivenKind(T_DOUBLE_COLON)) {
             return false;
             return false;
         }
         }
 
 
         $referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex);
         $referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex);
-        if (!$tokens->offsetExists($referenceIndex)) {
+
+        if (null === $referenceIndex) {
             return false;
             return false;
         }
         }
 
 

+ 1 - 0
src/Tokenizer/TokensAnalyzer.php

@@ -406,6 +406,7 @@ final class TokensAnalyzer
         while ($this->tokens[$prevIndex]->isGivenKind([CT::T_TYPE_ALTERNATION, T_STRING])) {
         while ($this->tokens[$prevIndex]->isGivenKind([CT::T_TYPE_ALTERNATION, T_STRING])) {
             $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex);
             $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex);
         }
         }
+
         if ($this->tokens[$prevIndex]->equals('(')) {
         if ($this->tokens[$prevIndex]->equals('(')) {
             $prevPrevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex);
             $prevPrevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex);
             if ($this->tokens[$prevPrevIndex]->isGivenKind(T_CATCH)) {
             if ($this->tokens[$prevPrevIndex]->isGivenKind(T_CATCH)) {

+ 1 - 1
tests/Fixer/ReturnNotation/ReturnAssignmentFixerTest.php

@@ -786,7 +786,7 @@ class XYZ
 {
 {
     public function test1()
     public function test1()
     {
     {
-        $GLOBALS = 2;
+        $GLOBALS[\'a\'] = 2;
 
 
         return $GLOBALS;
         return $GLOBALS;
     }
     }