Completed
Push — master ( afc88d...d0e6e6 )
by Mārtiņš
02:23
created

EmailIdentity::setHash()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2
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 EmailIdentity 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 $password;
22
    private $hash;
23
24
    protected $type = Identity::TYPE_PASSWORD;
25
26
27 5
    public function setIdentifier($identifier)
28
    {
29 5
        $this->identifier = (string) $identifier;
30 5
    }
31
32
33
    /**
34
     * @codeCoverageIgnore
35
     */
36
    public function getIdentifier()
37
    {
38
        return $this->identifier;
39
    }
40
41
42 1
    public function getFingerprint()
43
    {
44 1
        return hash('sha384', $this->identifier);
45
    }
46
47
48 3
    public function setPassword($password)
49
    {
50 3
        $this->password = (string) $password;
51 3
        $this->hash = $this->createHash($password);
52 3
    }
53
54
55
    /**
56
     * @codeCoverageIgnore
57
     */
58
    public function getHash()
59
    {
60
        return $this->hash;
61
    }
62
63
64 3
    private function createHash($password)
65
    {
66 3
        $hash = password_hash($password, self::HASH_ALGO, ['cost' => self::HASH_COST]);
67
68 3
        return $hash;
69
    }
70
71
72 3
    public function setHash($hash)
73
    {
74 3
        if (null === $hash) {
75 1
            $this->hash = null;
76 1
            return;
77
        }
78 3
        $this->hash = (string) $hash;
79 3
    }
80
81
82 1
    public function matchKey($password)
83
    {
84 1
        return password_verify($password, $this->hash);
85
    }
86
87
88 1
    public function isOldHash()
89
    {
90 1
        return password_needs_rehash($this->hash, self::HASH_ALGO, ['cost' => self::HASH_COST]);
91
    }
92
93
94 3
    public function validate()
95
    {
96 3
        if (false === filter_var($this->identifier, FILTER_VALIDATE_EMAIL)) {
97 1
            throw new InvalidEmail;
98
        }
99
100 2
        if (strlen($this->password) < self::MIN_LENGTH || strlen($this->password) > self::MAX_LENGTH) {
101 1
            throw new InvalidPassword;
102
        }
103 1
    }
104
}
105