Simple2   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 95.83%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 19
c 1
b 0
f 1
dl 0
loc 49
ccs 23
cts 24
cp 0.9583
rs 10
wmc 12

6 Methods

Rating   Name   Duplication   Size   Complexity  
A checkToken() 0 6 4
A getToken() 0 7 2
A removeToken() 0 4 2
A init() 0 4 1
A getSession() 0 8 2
A getExpire() 0 3 1
1
<?php
2
3
namespace kalanis\kw_forms\Controls\Security\Csrf;
4
5
6
use ArrayAccess;
7
use kalanis\kw_forms\Interfaces\ICsrf;
8
9
10
/**
11
 * Class Simple2
12
 * Secure forms by simple tokens
13
 * @package kalanis\kw_forms\Controls\Security\Csrf
14
 */
15
class Simple2 implements ICsrf
16
{
17
    protected ?ArrayAccess $session = null;
18
    protected int $expire = 3600;
19
20 1
    public function init(ArrayAccess &$cookie, int $expire = 3600): void
21
    {
22 1
        $this->session = $cookie;
23 1
        $this->expire = $expire;
24 1
    }
25
26 1
    public function removeToken(string $codeName): void
27
    {
28 1
        if ($this->getSession()->offsetExists($codeName)) {
29 1
            $this->getSession()->offsetUnset($codeName);
30
        }
31 1
    }
32
33 1
    public function getToken(string $codeName): string
34
    {
35 1
        if (!$this->getSession()->offsetExists($codeName)) {
36 1
            $this->getSession()->offsetSet($codeName, bin2hex(random_bytes(64)));
37 1
            $this->getSession()->offsetSet($codeName . '_timer', time() + $this->expire);
38
        }
39 1
        return strval($this->getSession()->offsetGet($codeName));
40
    }
41
42 1
    public function getExpire(): int
43
    {
44 1
        return $this->expire;
45
    }
46
47 1
    public function checkToken(string $token, string $codeName): bool
48
    {
49 1
        return $this->getSession()->offsetExists($codeName)
50 1
                && $this->getSession()->offsetExists($codeName . '_timer')
51 1
                && $this->getSession()->offsetGet($codeName) == $token
52 1
                && $this->getSession()->offsetGet($codeName . '_timer') > time()
53
                ;
54
    }
55
56 1
    protected function getSession(): ArrayAccess
57
    {
58 1
        if (!empty($this->session)) {
59 1
            return $this->session;
60
        }
61
        // @codeCoverageIgnoreStart
62
        // you need to whant session before call that sets the control
63
        throw new \LogicException('Set the session first!');
64
        // @codeCoverageIgnoreEnd
65
    }
66
}
67