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

Random   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 66.67%

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 6
c 6
b 0
f 0
lcom 0
cbo 0
dl 0
loc 52
ccs 8
cts 12
cp 0.6667
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A toss() 0 7 1
A fromMcrypt() 0 10 2
A bytes() 0 10 3
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