Completed
Push — master ( ee148f...3aab2e )
by Michael
02:37
created

Random::get()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.7085

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 10
ccs 4
cts 7
cp 0.5714
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
crap 3.7085
1
<?php
2
3
/**
4
 * Random.php
5
 * 
6
 * PHP version 5
7
 * 
8
 * @category Dcrypt
9
 * @package  Dcrypt
10
 * @author   Michael Meyer (mmeyer2k) <[email protected]>
11
 * @license  http://opensource.org/licenses/MIT The MIT License (MIT)
12
 * @link     https://github.com/mmeyer2k/dcrypt
13
 * @link     https://apigen.ci/github/mmeyer2k/dcrypt
14
 */
15
16
namespace Dcrypt;
17
18
/**
19
 * Fail-safe wrapper for mcrypt_create_iv (preferably) and
20
 * openssl_random_pseudo_bytes (fallback).
21
 *
22
 * @category Dcrypt
23
 * @package  Dcrypt
24
 * @author   Michael Meyer (mmeyer2k) <[email protected]>
25
 * @license  http://opensource.org/licenses/MIT The MIT License (MIT)
26
 * @link     https://github.com/mmeyer2k/dcrypt
27
 * @link     https://apigen.ci/github/mmeyer2k/dcrypt/class-Dcrypt.Random.html
28
 */
29
final class Random
30
{
31
32
    /**
33
     * Get random bytes from Mcrypt
34
     * 
35
     * @param int $bytes Number of bytes to get
36
     * 
37
     * @return string
38
     */
39 14
    private static function fromMcrypt($bytes)
40
    {
41 14
        $ret = \mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM);
42
43 14
        if ($ret === false) {
44
            self::toss(); // @codeCoverageIgnore
45
        }
46
47 14
        return $ret;
48
    }
49
50
    /**
51
     * Return securely generated random bytes.
52
     * 
53
     * @param int  $bytes  Number of bytes to get
54
     * 
55
     * @return string
56
     */
57 14
    public static function bytes($bytes)
58
    {
59 14
        if (\function_exists('random_bytes')) {
60
            return \random_bytes($bytes);
61 14
        } elseif (\function_exists('mcrypt_create_iv')) {
62 14
            return self::fromMcrypt($bytes);
63
        }
64
        
65
        self::toss();
66
    }
67
68
    /*
69
     * Throw an error when a failure occurs.
70
     */
71
72
    private static function toss()
73
    {
74
        // @codeCoverageIgnoreStart
75
        $e = 'Dcrypt failed to generate a random number';
76
        throw new \exception($e);
77
        // @codeCoverageIgnoreEnd
78
    }
79
80
}
81