getPseudoRandomString()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 16
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Maztech\PseudoRandomString;
4
5
use Maztech\Exceptions\InstagramSDKException;
6
7
class OpenSslPseudoRandomStringGenerator implements PseudoRandomStringGeneratorInterface
8
{
9
    use PseudoRandomStringGeneratorTrait;
10
11
    /**
12
     * @const string The error message when generating the string fails.
13
     */
14
    const ERROR_MESSAGE = 'Unable to generate a cryptographically secure pseudo-random string from openssl_random_pseudo_bytes().';
15
16
    /**
17
     * @throws InstagramSDKException
18
     */
19
    public function __construct()
20
    {
21
        if (!function_exists('openssl_random_pseudo_bytes')) {
22
            throw new InstagramSDKException(static::ERROR_MESSAGE . 'The function openssl_random_pseudo_bytes() does not exist.');
23
        }
24
    }
25
26
    /**
27
     * @inheritdoc
28
     */
29
    public function getPseudoRandomString($length)
30
    {
31
        $this->validateLength($length);
32
33
        $wasCryptographicallyStrong = false;
34
        $binaryString = openssl_random_pseudo_bytes($length, $wasCryptographicallyStrong);
35
36
        if ($binaryString === false) {
37
            throw new InstagramSDKException(static::ERROR_MESSAGE . 'openssl_random_pseudo_bytes() returned an unknown error.');
38
        }
39
40
        if ($wasCryptographicallyStrong !== true) {
41
            throw new InstagramSDKException(static::ERROR_MESSAGE . 'openssl_random_pseudo_bytes() returned a pseudo-random string but it was not cryptographically secure and cannot be used.');
42
        }
43
44
        return $this->binToHex($binaryString, $length);
45
    }
46
}
47