Completed
Push — master ( 295b1b...70c635 )
by Oliver
05:25 queued 03:24
created

OpenSslGenerator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 47
ccs 0
cts 15
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getRandomInt() 0 11 4
1
<?php
2
3
namespace TQ\Shamir\Random;
4
5
/**
6
 * Class OpenSslGenerator
7
 *
8
 * Generate a pseudo-random string of bytes using the OpenSSL library.
9
 *
10
 * @package TQ\Shamir\Random
11
 */
12
class OpenSslGenerator implements Generator
13
{
14
15
    /**
16
     * Length of the desired string of bytes
17
     *
18
     * @var int
19
     */
20
    protected $bytes = PHP_INT_SIZE;
21
22
    /**
23
     * Force strong random number generation or "die"
24
     *
25
     * @var bool
26
     */
27
    protected $forceStrong = true;
28
29
    /**
30
     * Constructor
31
     *
32
     * @param int $bytes Bytes to use in result
33
     * @param int $forceStrong Force strong random number generation
34
     */
35
    public function __construct($bytes = PHP_INT_SIZE, $forceStrong = true)
36
    {
37
        $this->bytes = (int)$bytes;
38
        $this->forceStrong = (bool)$forceStrong;
39
    }
40
41
    /**
42
     * @inheritdoc
43
     * @see http://php.net/manual/en/function.openssl-random-pseudo-bytes.php
44
     * @throws \RuntimeException
45
     */
46
    public function getRandomInt()
47
    {
48
        $random = openssl_random_pseudo_bytes($this->bytes, $strong);
49
        if ($random === null || ($this->forceStrong && $strong !== true)) {
50
            throw new \RuntimeException(
51
                'Random number generator algorithm didn\'t used "cryptographically strong" method.'
52
            );
53
        }
54
55
        return hexdec(bin2hex($random));
56
    }
57
58
}