Skip to content

RandomApiMigration ​

warning on by default quick-fix

Group: Compatibility · PhpStorm name: RandomApiMigrationInspection

The libc-based rand() family is weaker and slower than the Mersenne Twister family (mt_*), and since PHP 7.0 random_int() provides a CSPRNG integer. Suggest renaming legacy random calls to their modern counterpart.

Example ​

Option SUGGEST_USING_RANDOM_INT = false (any level):

php
<?php
srand(1234);
$cap  = getrandmax();
$roll = \rand(1, 6);
$keep = mt_rand(1, 6);
php
<?php
mt_srand(1234);
$cap  = mt_getrandmax();
$roll = \mt_rand(1, 6);
$keep = mt_rand(1, 6);

Reported:

  • line 2: Prefer mt_srand() over srand().
  • line 3: Prefer mt_getrandmax() over getrandmax().
  • line 4: Prefer mt_rand() over rand().

Options ​

OptionTypeDefaultEffect
SUGGEST_USING_RANDOM_INTbooltrueWhen on and the level is 7.0+, rand/mt_rand with two arguments are pointed at random_int; when off, the classic table is used at every level.

Configure ​

In custos.json:

json
{
  "rules": {
    "RandomApiMigration": {
      "enabled": false,
      "options": {
        "SUGGEST_USING_RANDOM_INT": true
      }
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore RandomApiMigration

/**
 * @noinspection RandomApiMigrationInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.