Completed
Branch master (53fdb9)
by Mārtiņš
04:03 queued 01:53
created

PasswordIdentity::getFingerprint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Palladium\Entity;
4
5
use RuntimeException;
6
use Palladium\Exception\InvalidPassword;
7
use Palladium\Exception\InvalidEmail;
8
9
10
class PasswordIdentity extends Identity
11
{
12
13
    const HASH_ALGO = PASSWORD_BCRYPT;
14
    const HASH_COST = 12;
15
16
    const MIN_LENGTH = 6;
17
    const MAX_LENGTH = 128;
18
19
20
    private $identifier;
21
    private $key;
22
    private $hash;
23
24
    protected $type = Identity::TYPE_PASSWORD;
25
26
27
    public function setIdentifier($identifier)
28
    {
29
        $this->identifier = (string) $identifier;
30
    }
31
32
33
    /**
34
     * @codeCoverageIgnore
35
     */
36
    public function getIdentifier()
37
    {
38
        return $this->identifier;
39
    }
40
41
42
    public function getFingerprint()
43
    {
44
        return hash('sha384', $this->identifier);
45
    }
46
47
48
    public function setKey($key)
49
    {
50
        $this->key = (string) $key;
51
        $this->hash = $this->createHash($key);
52
    }
53
54
55
    /**
56
     * @codeCoverageIgnore
57
     */
58
    public function getHash()
59
    {
60
        return $this->hash;
61
    }
62
63
64
    private function createHash($key)
65
    {
66
        $hash = password_hash($key, self::HASH_ALGO, ['cost' => self::HASH_COST]);
67
68
        return $hash;
69
    }
70
71
72
    public function setHash($hash)
73
    {
74
        if (null === $hash) {
75
            $this->hash = null;
76
            return;
77
        }
78
        $this->hash = (string) $hash;
79
    }
80
81
82
    public function matchKey($key)
83
    {
84
        return password_verify($key, $this->hash);
85
    }
86
87
88
    public function isOldHash()
89
    {
90
        return password_needs_rehash($this->hash, self::HASH_ALGO, ['cost' => self::HASH_COST]);
91
    }
92
93
94
    public function validate()
95
    {
96
        if (false === filter_var($this->identifier, FILTER_VALIDATE_EMAIL)) {
97
            throw new InvalidEmail;
98
        }
99
100
        if (strlen($this->key) < self::MIN_LENGTH || strlen($this->key) > self::MAX_LENGTH) {
101
            throw new InvalidPassword;
102
        }
103
    }
104
}
105