Test Failed
Pull Request — master (#476)
by
unknown
03:09
created

UserPassword::getHash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\User;
6
7
use Yiisoft\Security\PasswordHasher;
8
use Yiisoft\Validator\Rule\HasLength;
9
use Yiisoft\Validator\Rule\Required;
10
use Yiisoft\Validator\SimpleRuleHandlerContainer;
11
use Yiisoft\Validator\Validator;
12
13
final class UserPassword
14
{
15
    private string $passwordHash;
16
    private PasswordHasher $hasher;
17
18
    private function __construct(private string $value)
19
    {
20
        $this->hasher = new PasswordHasher();
21
        $this->passwordHash = $this->hasher->hash($this->value);
22
    }
23
24
    public function getHash(): string
25
    {
26
        return $this->passwordHash;
27
    }
28
29
    public function isEqualHash(string $hash): bool
30
    {
31
        return $this->hasher->validate($this->value, $hash);
32
    }
33
34
    /**
35
     * @throw UserPasswordException
36
     */
37
    public static function createNew(string $password): UserPassword
38
    {
39
        $validator = new Validator(new SimpleRuleHandlerContainer());
40
        $rules = [
41
            new Required(),
42
            new HasLength(min: 8),
43
        ];
44
45
        $result = $validator->validate($password, $rules);
46
        if (!$result->isValid()) {
47
            foreach ($result->getErrorMessages() as $errorMessage) {
48
                throw new UserPasswordException($errorMessage);
49
            }
50
        }
51
52
        return new UserPassword($password);
53
    }
54
}
55