2

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.

1 Answer 1

3

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)));
      }
}
Sign up to request clarification or add additional context in comments.

1 Comment

For the sake of completeness, negative integers are also possible parameters for generateEncryptionKey().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.