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

McryptRandomStringGenerator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 2
dl 0
loc 52
ccs 0
cts 20
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A generateString() 0 16 2
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