Completed
Push — master ( 8e03fe...2e168d )
by Anthony
02:04
created

getBlacklistPasswords()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 6
1
<?php
2
declare(strict_types=1);
3
4
namespace Porthou\Password\Validators;
5
6
use Generator;
7
use Porthou\Password\PasswordException;
8
9
class PasswordPwnedListValidator
10
{
11
    /** @var string $file */
12
    private $file;
13
14
    /** @var int $minimumThreshold */
15
    private $minimumThreshold;
16
17
    /**
18
     * PasswordPwnedListValidator constructor.
19
     *
20
     * @param string $file the path to the blacklist file
21
     * @param int $minimumThreshold How many times a password must appear before we consider it invalid
22
     * @see https://haveibeenpwned.com/Passwords for access to the list of passwords to be used with this validator.
23
     */
24
    public function __construct(string $file, $minimumThreshold = 50)
25
    {
26
        $this->file = $file;
27
        $this->minimumThreshold = $minimumThreshold;
28
    }
29
30
    /** {@inheritdoc} */
31
    public function validate(string $password): bool
32
    {
33
        $passwordHash = sha1($password);
34
35
        foreach ($this->getBlacklistPasswords() as $badPassword) {
36
            [$badHash, $count] = $badPassword;
0 ignored issues
show
Bug introduced by
The variable $badHash does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $count does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
37
            if (
38
                $passwordHash === $badHash
39
                && $count >= $this->minimumThreshold
40
            ) {
41
                throw new PasswordException('Password has been pwned.');
42
            }
43
        }
44
45
        return true;
46
    }
47
48
    /**
49
     * Iterates over and yields each blacklisted password
50
     *
51
     * @return Generator
52
     */
53
    private function getBlacklistPasswords(): Generator
54
    {
55
        $fh = fopen($this->file, 'rb');
56
57
        while (($password = fgets($fh)) !== false) {
58
            yield explode(':', trim($password));
59
        }
60
61
        fclose($fh);
62
    }
63
}
64