Home > Blockchain >  PHPStan: Parameter #1 $length of function random_bytes expects int<1, max>, int given
PHPStan: Parameter #1 $length of function random_bytes expects int<1, max>, int given

Time:09-26

I'm getting a PHPStan error that I don't understand how to fix:

Parameter #1 $length of function random_bytes expects int<1, max>, int given.

The function is very simple:

  private function generateEncryptionKey(int $bytes = 16): string {
    return bin2hex(random_bytes($bytes));
  }

I don't know why the error is expects int<1, max> because I typehint $bytes to int and random_bytes takes an int as the argument.

So what is the meaning of the error PHPStan is identifying here, and how can I fix it?

The PHPStan online demo also reports this as an error.

CodePudding user response:

It expects to have a minimum of length 1, but you could call it with a length of 0 which would fail.

Fix

You can fix this by calling with a max(1, $bytes) which will have at least 1 byte, even if a 0 is passed.

Demo

Note

I changed to public static for testing purpose, but you can change back to private.

Code

class HelloWorld
{
      public static function generateEncryptionKey(int $bytes = 16): string {
          return bin2hex(random_bytes(max(1, $bytes)));
      }
}
  • Related