Completed
Push — master ( 7049ea...a58db8 )
by Magnar Ovedal
03:09
created

PasswordHash::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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