OpenSslGenerator::getRandomInt()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 5.2596

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 4
eloc 5
c 2
b 1
f 1
nc 2
nop 0
dl 0
loc 10
ccs 4
cts 7
cp 0.5714
crap 5.2596
rs 10
1
<?php
2
3
namespace TQ\Shamir\Random;
4
5
use OutOfRangeException;
6
use RuntimeException;
7
8
/**
9
 * Class OpenSslGenerator
10
 *
11
 * Generate a pseudo-random string of bytes using the OpenSSL library.
12
 *
13
 * @package TQ\Shamir\Random
14
 */
15
class OpenSslGenerator implements Generator
16
{
17
    /**
18
     * Length of the desired string of bytes
19
     *
20
     * @var int
21
     */
22
    protected $bytes = PHP_INT_SIZE;
23
24
    /**
25
     * Force strong random number generation or "die"
26
     *
27
     * @var bool
28
     */
29
    protected $forceStrong = true;
30
31
    /**
32
     * @param  int   $bytes        Bytes to use in the result
33
     * @param  bool  $forceStrong  Force strong random number generation
34
     */
35 5
    public function __construct(int $bytes = PHP_INT_SIZE, bool $forceStrong = true)
36
    {
37 5
        if ($bytes < 1) {
38 2
            throw new OutOfRangeException('The length of the desired string of bytes. Must be a positive integer.');
39
        }
40
41 3
        $this->bytes       = $bytes;
42 3
        $this->forceStrong = $forceStrong;
43
    }
44
45 1
    public function isForceStrong(): bool
46
    {
47 1
        return $this->forceStrong;
48
    }
49
50
    /**
51
     * @inheritdoc
52
     * @see https://php.net/manual/en/function.openssl-random-pseudo-bytes.php
53
     * @throws RuntimeException
54
     */
55 2
    public function getRandomInt()
56
    {
57 2
        $random = openssl_random_pseudo_bytes($this->bytes, $isSourceStrong);
58 2
        if ($random === false || ($this->forceStrong && $isSourceStrong !== true)) {
59
            throw new RuntimeException(
60
                'Random number generator algorithm didn\'t used "cryptographically strong" method.'
61
            );
62
        }
63
64 2
        return hexdec(bin2hex($random));
65
    }
66
}
67