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

Generator::generate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 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