Passed
Push — master ( 7f0553...e4fd87 )
by Magnar Ovedal
04:10
created

PasswordHasher   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 61
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A hash() 0 18 2
A errorHandler() 0 3 1
A __construct() 0 4 1
A compare() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stadly\PasswordPolice\HashFunction;
6
7
use ErrorException;
8
use RuntimeException;
9
use Stadly\PasswordPolice\HashFunction;
10
11
final class PasswordHasher implements HashFunction
12
{
13
    /**
14
     * @var int Algorithm.
15
     */
16
    private $algorithm;
17
18
    /**
19
     * @var array Options.
20
     */
21
    private $options;
22
23
    /**
24
     * See http://php.net/manual/en/function.password-hash.php for details.
25
     *
26
     * @param int $algorithm Algorithm.
27
     * @param array $options Options.
28
     */
29 1
    public function __construct(int $algorithm = PASSWORD_DEFAULT, array $options = [])
30
    {
31 1
        $this->algorithm = $algorithm;
32 1
        $this->options = $options;
33 1
    }
34
35
    /**
36
     * {@inheritDoc}
37
     */
38 2
    public function hash(string $password): string
39
    {
40 2
        set_error_handler([self::class, 'errorHandler']);
41
        try {
42 2
            $hash = password_hash($password, $this->algorithm, $this->options);
43 1
        } catch (ErrorException $exception) {
44 1
            throw new RuntimeException(
45 1
                'An error occurred while hashing the password: '.$exception->getMessage(),
46 1
                /*code*/0,
47 1
                $exception
48
            );
49 1
        } finally {
50 2
            restore_error_handler();
51
        }
52
53 1
        assert($hash !== false);
54
55 1
        return $hash;
56
    }
57
58
    /**
59
     * {@inheritDoc}
60
     */
61 2
    public function compare(string $password, string $hash): bool
62
    {
63 2
        return password_verify($password, $hash);
64
    }
65
66
    /**
67
     * @throws ErrorException Error converted to an exception.
68
     */
69 1
    private static function errorHandler(int $severity, string $message, string $filename, int $line): void
70
    {
71 1
        throw new ErrorException($message, /*code*/0, $severity, $filename, $line);
72
    }
73
}
74