Completed
Push — master ( 2994aa...19d116 )
by Patrick
08:28
created

McryptRandomStringGenerator::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.5

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 3
cts 6
cp 0.5
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2.5
1
<?php
2
namespace Dropbox\Security;
3
4
use Dropbox\Exceptions\DropboxClientException;
5
6
/**
7
 * @inheritdoc
8
 */
9
class McryptRandomStringGenerator implements RandomStringGeneratorInterface
10
{
11
    use RandomStringGeneratorTrait;
12
13
    /**
14
     * The error message when generating the string fails.
15
     *
16
     * @const string
17
     */
18
    const ERROR_MESSAGE = 'Unable to generate a cryptographically secure pseudo-random string from mcrypt_create_iv(). ';
19
20
    /**
21
     * Create a new McryptRandomStringGenerator instance
22
     *
23
     * @throws \Dropbox\Exceptions\DropboxClientException
24
     */
25 58
    public function __construct()
26
    {
27 58
        if (!function_exists('mcrypt_create_iv')) {
28
            throw new DropboxClientException(
29
                static::ERROR_MESSAGE .
30
                'The function mcrypt_create_iv() does not exist.'
31
                );
32
        }
33 58
    }
34
35
    /**
36
     * Get a randomly generated secure token
37
     *
38
     * @param  int $length Length of the string to return
39
     *
40
     * @throws \Dropbox\Exceptions\DropboxClientException
41
     *
42
     * @return string
43
     */
44
    public function generateString($length)
45
    {
46
        //Create Binary String
47
        $binaryString = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
48
49
        //Unable to create binary string
50
        if ($binaryString === false) {
51
            throw new DropboxClientException(
52
                static::ERROR_MESSAGE .
53
                'mcrypt_create_iv() returned an error.'
54
                );
55
        }
56
57
        //Convert binary to hex
58
        return $this->binToHex($binaryString, $length);
59
    }
60
}
61