Internal::isValidResult()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 3
eloc 2
nc 3
nop 3
crap 3
1
<?php
2
3
namespace Riimu\Kit\SecureRandom\Generator;
4
5
use Riimu\Kit\SecureRandom\GeneratorException;
6
7
/**
8
 * Generates bytes and numbers using PHP's built in CSPRNG.
9
 *
10
 * PHP7 offers a built in function for generating cryptographically secure
11
 * random bytes. This class simply wraps that method for supported PHP versions.
12
 *
13
 * @author Riikka Kalliomäki <[email protected]>
14
 * @copyright Copyright (c) 2015-2017 Riikka Kalliomäki
15
 * @license http://opensource.org/licenses/mit-license.php MIT License
16
 */
17
class Internal extends AbstractGenerator implements NumberGenerator
18
{
19 9
    public function isSupported()
20
    {
21 9
        return version_compare(PHP_VERSION, '7.0') >= 0;
22
    }
23
24 2
    protected function readBytes($count)
25
    {
26 2
        return random_bytes($count);
27
    }
28
29 4
    public function getNumber($min, $max)
30
    {
31 4
        $min = (int) $min;
32 4
        $max = (int) $max;
33 4
        $exception = null;
34
35
        try {
36 4
            $number = random_int($min, $max);
37 2
        } catch (\Throwable $exception) {
38 2
            $number = false;
39
        }
40
41 4
        if (!$this->isValidResult($number, $min, $max)) {
42 2
            throw new GeneratorException('Error generating random number', 0, $exception);
43
        }
44
45 2
        return $number;
46
    }
47
48
    /**
49
     * Tells if the generated number is a valid result.
50
     * @param int $number The number to test
51
     * @param int $min The minimum value for the number
52
     * @param int $max The maximum value for the number
53
     * @return bool True if the number is a valid result, false if not
54
     */
55 4
    private function isValidResult($number, $min, $max)
56
    {
57 4
        return is_int($number) && $number >= $min && $number <= $max;
58
    }
59
}
60