UrandomPseudoRandomStringGenerator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 60
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 3
A getPseudoRandomString() 0 27 4
1
<?php
2
3
namespace Maztech\PseudoRandomString;
4
5
use Maztech\Exceptions\InstagramSDKException;
6
7
class UrandomPseudoRandomStringGenerator implements PseudoRandomStringGeneratorInterface
8
{
9
10
    use PseudoRandomStringGeneratorTrait;
11
12
    /**
13
     * @const string The error message when generating the string fails.
14
     */
15
    const ERROR_MESSAGE = 'Unable to generate a cryptographically secure pseudo-random string from /dev/urandom. ';
16
17
    /**
18
     * @throws InstagramSDKException
19
     */
20
    public function __construct()
21
    {
22
        if (ini_get('open_basedir')) {
23
            throw new InstagramSDKException(
24
                static::ERROR_MESSAGE .
25
                'There is an open_basedir constraint that prevents access to /dev/urandom.'
26
            );
27
        }
28
29
        if (!is_readable('/dev/urandom')) {
30
            throw new InstagramSDKException(
31
                static::ERROR_MESSAGE .
32
                'Unable to read from /dev/urandom.'
33
            );
34
        }
35
    }
36
37
    /**
38
     * @inheritdoc
39
     */
40
    public function getPseudoRandomString($length)
41
    {
42
        $this->validateLength($length);
43
44
        $stream = fopen('/dev/urandom', 'rb');
45
        if (!is_resource($stream)) {
46
            throw new InstagramSDKException(
47
                static::ERROR_MESSAGE .
48
                'Unable to open stream to /dev/urandom.'
49
            );
50
        }
51
52
        if (!defined('HHVM_VERSION')) {
53
            stream_set_read_buffer($stream, 0);
54
        }
55
56
        $binaryString = fread($stream, $length);
57
        fclose($stream);
58
59
        if (!$binaryString) {
60
            throw new InstagramSDKException(
61
                static::ERROR_MESSAGE .
62
                'Stream to /dev/urandom returned no data.'
63
            );
64
        }
65
66
        return $this->binToHex($binaryString, $length);
67
    }
68
}
69