Passed
Pull Request — master (#20)
by Hilmi Erdem
13:59 queued 07:56
created

NumericGenerator::generate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 11
rs 10
1
<?php
2
3
/*
4
 * @copyright 2021 Hilmi Erdem KEREN
5
 * @license MIT
6
 */
7
8
namespace Erdemkeren\Otp\Generators;
9
10
use Erdemkeren\Otp\Contracts\GeneratorContract;
11
use Throwable;
12
13
/**
14
 * Class NumericGenerator.
15
 */
16
class NumericGenerator implements GeneratorContract
17
{
18
    /**
19
     * Generate a numeric password.
20
     *
21
     * @return string
22
     */
23
    public function generate(): string
24
    {
25
        $range = $this->generateRangeForLength();
26
27
        try {
28
            $int = random_int($range[0], $range[1]);
29
        } catch (Throwable) {
30
            $int = rand($range[0], $range[1]);
31
        }
32
33
        return (string) $int;
34
    }
35
36
    /**
37
     * Generate the required range for the given length.
38
     *
39
     * @return array
40
     */
41
    protected function generateRangeForLength(): array
42
    {
43
        $min = 1;
44
        $max = 9;
45
        $length = 8;
46
47
        while ($length > 1) {
48
            $min .= 0;
49
            $max .= 9;
50
51
            $length--;
52
        }
53
54
        return [
55
            $min, $max,
56
        ];
57
    }
58
}
59