PasswordHasher   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 18
c 2
b 0
f 0
dl 0
loc 56
ccs 20
cts 20
cp 1
rs 10
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<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