forked from muglug/psl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
int.php
37 lines (30 loc) · 1019 Bytes
/
int.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
declare(strict_types=1);
namespace Psl\SecureRandom;
use Exception as PHPException;
use Psl;
use Psl\Math;
use Psl\Str;
use Psl\Type;
use function random_int;
/**
* Returns a cryptographically secure random integer in the range in the given range.
*
* @throws Exception\InsufficientEntropyException If it was not possible to gather sufficient entropy.
* @throws Psl\Exception\InvariantViolationException If $min > $max.
*/
function int(int $min = Math\INT64_MIN, int $max = Math\INT64_MAX): int
{
Psl\invariant($min <= $max, 'Expected $min (%d) to be less than or equal to $max (%d).', $min, $max);
try {
return random_int($min, $max);
// @codeCoverageIgnoreStart
} catch (PHPException $e) {
$code = $e->getCode();
if (Type\string()->matches($code)) {
$code = Str\to_int($code) ?? 0;
}
throw new Exception\InsufficientEntropyException('Unable to gather sufficient entropy.', $code, $e);
// @codeCoverageIgnoreEnd
}
}