Passed
Push — main ( 7dcca1...e70bce )
by Daniel
04:22
created

PasswordVerificator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 10
c 2
b 0
f 0
dl 0
loc 51
ccs 13
cts 13
cp 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Uxmp\Core\Component\User;
6
7
use SensitiveParameter;
8
use Uxmp\Core\Orm\Model\UserInterface;
9
use Uxmp\Core\Orm\Repository\UserRepositoryInterface;
10
11
/**
12
 * Utility methods for password verification, hashing, ...
13
 */
14
final readonly class PasswordVerificator implements PasswordVerificatorInterface
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 14 at column 6
Loading history...
15
{
16
    /**
17
     * @var int
18
     */
19
    public const PASSWORD_MIN_LENGTH = 6;
20
21
    /**
22
     * @param array<string, mixed> $passwordOptions
23
     */
24 4
    public function __construct(
25
        private UserRepositoryInterface $userRepository,
26
        private string $defaultAlgo = PASSWORD_DEFAULT,
27
        private array $passwordOptions = [],
28
    ) {
29 4
    }
30
31
    /**
32
     * Verifies the users' password input
33
     *
34
     * Also performs a migration of the password hash if necessary
35
     *
36
     * @return bool `True` if validation was successful
37
     */
38 3
    public function verify(
39
        UserInterface $user,
40
        #[SensitiveParameter]
41
        string $password
42
    ): bool {
43 3
        $hash = $user->getPassword();
44
45 3
        $result = password_verify($password, $hash);
46
47 3
        if ($result && password_needs_rehash($hash, $this->defaultAlgo, $this->passwordOptions)) {
48 1
            $user->setPassword(
49 1
                $this->hash($password)
50 1
            );
51 1
            $this->userRepository->save($user);
52
        }
53
54 3
        return $result;
55
    }
56
57
    /**
58
     * Hashes a password
59
     */
60 2
    public function hash(
61
        #[SensitiveParameter]
62
        string $password
63
    ): string {
64 2
        return password_hash($password, $this->defaultAlgo, $this->passwordOptions);
65
    }
66
}
67