SessionTokenStore   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 70
c 0
b 0
f 0
wmc 8
lcom 1
cbo 0
ccs 0
cts 28
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A registerToken() 0 18 4
A verifyToken() 0 14 3
A getClientSalt() 0 4 1
1
<?php
2
3
namespace mindplay\kissform\Framework;
4
5
use mindplay\kissform\Facets\TokenStoreInterface;
6
use RuntimeException;
7
8
/**
9
 * This class implements a token store using `$_SESSION`.
10
 */
11
class SessionTokenStore implements TokenStoreInterface
12
{
13
    /**
14
     * @var int hard limit for unique tokens stored per user session
15
     */
16
    const HARD_LIMIT = 10;
17
18
    /**
19
     * @var bool[] map of tokens validated and consumed during the lifetime of this object
20
     */
21
    private $valid = [];
22
23
    /**
24
     * @inheritdoc
25
     *
26
     * @throws RuntimeException
27
     *
28
     * @SuppressWarnings(Superglobals)
29
     */
30
    public function registerToken($token)
31
    {
32
        if (!session_id()) {
33
            throw new RuntimeException("no active session");
34
        }
35
36
        if (!isset($_SESSION[__CLASS__])) {
37
            $_SESSION[__CLASS__] = [];
38
        }
39
40
        $_SESSION[__CLASS__][$token] = true;
41
42
        if (count($_SESSION[__CLASS__]) > self::HARD_LIMIT) {
43
            // truncate garbage tokens (which may accummulate if the user keeps hitting "refresh")
44
45
            $_SESSION[__CLASS__] = array_slice($_SESSION[__CLASS__], -self::HARD_LIMIT, null, true);
46
        }
47
    }
48
49
    /**
50
     * @inheritdoc
51
     *
52
     * @throws RuntimeException
53
     *
54
     * @SuppressWarnings(Superglobals)
55
     */
56
    public function verifyToken($token)
57
    {
58
        if (!session_id()) {
59
            throw new RuntimeException("no active session");
60
        }
61
62
        if (isset($_SESSION[__CLASS__][$token])) {
63
            unset($_SESSION[__CLASS__][$token]);
64
65
            $this->valid[$token] = true;
66
        }
67
68
        return isset($this->valid[$token]);
69
    }
70
71
    /**
72
     * @inheritdoc
73
     *
74
     * @SuppressWarnings(Superglobals)
75
     */
76
    public function getClientSalt()
77
    {
78
        return @$_SERVER['REMOTE_ADDR'] . @$_SERVER['HTTP_USER_AGENT'] . session_id();
79
    }
80
}
81