Completed
Push — master ( 4d4232...ffcfa4 )
by Anthony
14:02 queued 11:53
created

URandom::generate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 15
rs 9.2
cc 4
eloc 11
nc 4
nop 1
1
<?php
2
/**
3
 * The URandom Random Number Source
4
 *
5
 * This uses the *nix /dev/urandom device to generate medium strength numbers
6
 *
7
 * PHP version 5.3
8
 *
9
 * @category   PHPCryptLib
10
 * @package    Random
11
 * @subpackage Source
12
 * @author     Anthony Ferrara <[email protected]>
13
 * @copyright  2011 The Authors
14
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
15
 * @version    Build @@version@@
16
 */
17
18
namespace RandomLib\Source;
19
20
use SecurityLib\Strength;
21
22
/**
23
 * The URandom Random Number Source
24
 *
25
 * This uses the *nix /dev/urandom device to generate medium strength numbers
26
 *
27
 * @category   PHPCryptLib
28
 * @package    Random
29
 * @subpackage Source
30
 * @author     Anthony Ferrara <[email protected]>
31
 * @codeCoverageIgnore
32
 */
33
class URandom extends \RandomLib\AbstractSource {
34
35
    /**
36
     * @var string The file to read from
37
     */
38
    protected static $file = '/dev/urandom';
39
40
    /**
41
     * Return an instance of Strength indicating the strength of the source
42
     *
43
     * @return \SecurityLib\Strength An instance of one of the strength classes
44
     */
45
    public static function getStrength() {
46
        return new Strength(Strength::MEDIUM);
47
    }
48
49
    /**
50
     * If the source is currently available.
51
     * Reasons might be because the library is not installed
52
     *
53
     * @return boolean
54
     */
55
    public static function isSupported()
56
    {
57
        return @file_exists(static::$file);
58
    }
59
60
    /**
61
     * Generate a random string of the specified size
62
     *
63
     * @param int $size The size of the requested random string
64
     *
65
     * @return string A string of the requested size
66
     */
67
    public function generate($size) {
68
        if ($size == 0) {
69
            return static::emptyValue($size);
70
        }
71
        $file = fopen(static::$file, 'rb');
72
        if (!$file) {
73
            return static::emptyValue($size);
74
        }
75
        if (function_exists('stream_set_read_buffer')) {
76
            stream_set_read_buffer($file, 0);
77
        }
78
        $result = fread($file, $size);
79
        fclose($file);
80
        return $result;
81
    }
82
83
}
84