Completed
Push — master ( bcf360...98d48e )
by Abdala
03:37
created

Generator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 88.24%

Importance

Changes 0
Metric Value
wmc 5
eloc 16
dl 0
loc 39
ccs 15
cts 17
cp 0.8824
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A generate() 0 12 2
A __construct() 0 4 1
A __invoke() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace CustomerGauge\Password;
6
7
use CustomerGauge\Password\Exception\InvalidPassword;
8
use function random_int;
9
use function strlen;
10
11
final class Generator
12
{
13
    /** @var Rule */
14
    private $rule;
15
16
    /** @var int */
17
    private $length;
18
19 1
    public function __construct(Rule $rule, int $length = 12)
20
    {
21 1
        $this->rule   = $rule;
22 1
        $this->length = $length;
23 1
    }
24
25 1
    public function __invoke() : string
26
    {
27
        try {
28 1
            $password = $this->generate();
29
30 1
            $this->rule->__invoke($password);
31
32 1
            return $password;
33
        } catch (InvalidPassword $e) {
34
            return $this->__invoke();
35
        }
36
    }
37
38 1
    public function generate() : string
39
    {
40 1
        $chars    = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';
41 1
        $password = '';
42
43 1
        $max = strlen($chars) - 1;
44
45 1
        for ($i = 0; $i < $this->length; $i++) {
46 1
            $password .= $chars[random_int(0, $max)];
47
        }
48
49 1
        return $password;
50
    }
51
}
52