PasswordHasher::errorHandler()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 4
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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<string, string|int> 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<string, string|int> $options Options.
28
     */
29 4
    public function __construct(int $algorithm = PASSWORD_DEFAULT, array $options = [])
30
    {
31 4
        $this->algorithm = $algorithm;
32 4
        $this->options = $options;
33 4
    }
34
35 2
    public function hash(string $password): string
36
    {
37 2
        set_error_handler([self::class, 'errorHandler']);
38
        try {
39 2
            $hash = password_hash($password, $this->algorithm, $this->options);
40 1
        } catch (ErrorException $exception) {
41 1
            throw new RuntimeException(
42 1
                'An error occurred while hashing the password: ' . $exception->getMessage(),
43 1
                /*code*/0,
44 1
                $exception
45
            );
46 1
        } finally {
47 2
            restore_error_handler();
48
        }
49
50 1
        assert($hash !== false);
51
52 1
        return $hash;
53
    }
54
55 2
    public function compare(string $password, string $hash): bool
56
    {
57 2
        return password_verify($password, $hash);
58
    }
59
60
    // phpcs:disable SlevomatCodingStandard.Classes.UnusedPrivateElements.UnusedMethod
61
    /**
62
     * @throws ErrorException Error converted to an exception.
63
     */
64 1
    private static function errorHandler(int $severity, string $message, string $filename, int $line): bool
65
    {
66 1
        throw new ErrorException($message, /*code*/0, $severity, $filename, $line);
67
    }
68
    // phpcs:enable
69
}
70