Completed
Push — master ( 83241a...8e03fe )
by Anthony
03:35
created

PasswordBlacklistValidator::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
ccs 0
cts 9
cp 0
rs 9.4285
cc 3
eloc 5
nc 3
nop 1
crap 12
1
<?php
2
declare(strict_types=1);
3
4
namespace Porthou\Password\Validators;
5
6
use Generator;
7
use Porthou\Password\PasswordException;
8
use Porthou\Password\Validator;
9
10
class PasswordBlacklistValidator implements Validator
11
{
12
    /** @var string $file */
13
    private $file;
14
15
    public function __construct(string $file = null)
16
    {
17
        if ($file !== null) {
18
            $this->file = $file;
19
        } else {
20
            $this->file = __DIR__ . '/../../res/top_10000.txt';
21
        }
22
    }
23
24
    /** {@inheritdoc} */
25
    public function validate(string $password): bool
26
    {
27
        foreach ($this->getBlacklistPasswords() as $badPassword) {
28
            if ($password === $badPassword) {
29
                throw new PasswordException('Password is blacklisted.');
30
            }
31
        }
32
33
        return true;
34
    }
35
36
    /**
37
     * Iterates over and yields each blacklisted password
38
     *
39
     * @return Generator
40
     */
41
    private function getBlacklistPasswords(): Generator
42
    {
43
        $fh = fopen($this->file, 'rb');
44
45
        while (($password = fgets($fh)) !== false) {
46
            yield trim($password);
47
        }
48
49
        fclose($fh);
50
    }
51
}
52