Completed
Push — v3.0.0-dev ( c7f980...54069c )
by Hilmi Erdem
28:15
created

NumericPasswordGenerator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 0
dl 0
loc 46
rs 10
c 0
b 0
f 0
ccs 0
cts 23
cp 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A generate() 0 12 2
A generateRangeForLength() 0 16 2
1
<?php
2
3
/*
4
 * @copyright 2018 Hilmi Erdem KEREN
5
 * @license MIT
6
 */
7
8
namespace Erdemkeren\TemporaryAccess\PasswordGenerators;
9
10
use Exception;
11
use Erdemkeren\TemporaryAccess\PasswordGeneratorInterface;
12
13
/**
14
 * Class NumericPasswordGenerator.
15
 */
16
class NumericPasswordGenerator implements PasswordGeneratorInterface
17
{
18
    /**
19
     * Generate a numeric password.
20
     *
21
     * @param int $length
22
     *
23
     * @return string
24
     */
25
    public function generate(int $length): string
26
    {
27
        $range = $this->generateRangeForLength($length);
28
29
        try {
30
            $int = random_int($range[0], $range[1]);
31
        } catch (Exception $e) {
32
            $int = rand($range[0], $range[1]);
33
        }
34
35
        return (string) $int;
36
    }
37
38
    /**
39
     * Generate the required range for the given length.
40
     *
41
     * @param int $length
42
     *
43
     * @return array
44
     */
45
    protected function generateRangeForLength(int $length): array
46
    {
47
        $min = 1;
48
        $max = 9;
49
50
        while ($length > 1) {
51
            $min .= 0;
52
            $max .= 9;
53
54
            --$length;
55
        }
56
57
        return [
58
            $min, $max,
59
        ];
60
    }
61
}
62