Completed
Push — master ( 357a92...40d5af )
by Artem
05:29
created

ResetPasswordTrait::isResetTokenValid()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
crap 3
1
<?php
2
3
//----------------------------------------------------------------------
4
//
5
//  Copyright (C) 2017 Artem Rodygin
6
//
7
//  You should have received a copy of the MIT License along with
8
//  this file. If not, see <http://opensource.org/licenses/MIT>.
9
//
10
//----------------------------------------------------------------------
11
12
namespace Pignus\Model;
13
14
use Doctrine\ORM\Mapping as ORM;
15
use Ramsey\Uuid\Uuid;
16
17
/**
18
 * Trait for "reset password" feature.
19
 */
20
trait ResetPasswordTrait
21
{
22
    /**
23
     * @var string Reset token.
24
     *
25
     * @ORM\Column(name="reset_token", type="string", length=32, nullable=true)
26
     */
27
    protected $resetToken;
28
29
    /**
30
     * @var int Unix Epoch timestamp when the reset token expires.
31
     *
32
     * @ORM\Column(name="reset_token_expires_at", type="integer", nullable=true)
33
     */
34
    protected $resetTokenExpiresAt;
35
36
    /**
37
     * Generates new reset token which expires in specified period of time.
38
     *
39
     * @param \DateInterval $interval
40
     *
41
     * @return string Generated token.
42
     */
43 1
    public function generateResetToken(\DateInterval $interval)
44
    {
45 1
        $now = new \DateTime();
46
47 1
        $this->resetToken          = Uuid::uuid4()->getHex();
48 1
        $this->resetTokenExpiresAt = $now->add($interval)->getTimestamp();
49
50 1
        return $this->resetToken;
51
    }
52
53
    /**
54
     * Clears current reset token.
55
     *
56
     * @return self
57
     */
58 1
    public function clearResetToken()
59
    {
60 1
        $this->resetToken          = null;
61 1
        $this->resetTokenExpiresAt = null;
62
63 1
        return $this;
64
    }
65
66
    /**
67
     * Checks whether specified reset token is valid.
68
     *
69
     * @param string $token
70
     *
71
     * @return bool
72
     */
73 1
    public function isResetTokenValid(string $token)
74
    {
75
        return
76 1
            $this->resetToken === $token        &&
77 1
            $this->resetTokenExpiresAt !== null &&
78 1
            $this->resetTokenExpiresAt > time();
79
    }
80
}
81