CsrfTokenManager   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 12
c 0
b 0
f 0
dl 0
loc 51
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A removeToken() 0 4 2
A tokenWithId() 0 7 2
A isTokenValid() 0 7 2
A __construct() 0 4 1
A refreshToken() 0 5 1
1
<?php
2
3
/**
4
 * This file is part of web-stack
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Slick\WebStack\Domain\Security\Csrf;
13
14
/**
15
 * CsrfTokenManager
16
 *
17
 * @package Slick\WebStack\Domain\Security\Csrf
18
 */
19
final class CsrfTokenManager implements CsrfTokenManagerInterface
20
{
21
22
    public function __construct(
23
        private readonly TokenStorageInterface $storage,
24
        private readonly TokenGeneratorInterface $generator
25
    ) {
26
    }
27
28
    /**
29
     * @inheritDoc
30
     */
31
    public function tokenWithId(string $tokenId): CsrfToken
32
    {
33
        if ($this->storage->has($tokenId)) {
34
            return new CsrfToken($tokenId, $this->storage->get($tokenId));
35
        }
36
37
        return $this->refreshToken($tokenId);
38
    }
39
40
    /**
41
     * @inheritDoc
42
     */
43
    public function refreshToken(string $tokenId): CsrfToken
44
    {
45
        $token = new CsrfToken($tokenId, $this->generator->generateToken());
46
        $this->storage->set($tokenId, $token->value());
47
        return $token;
48
    }
49
50
    /**
51
     * @inheritDoc
52
     */
53
    public function removeToken(string $tokenId): void
54
    {
55
        if ($this->storage->has($tokenId)) {
56
            $this->storage->remove($tokenId);
57
        }
58
    }
59
60
    /**
61
     * @inheritDoc
62
     */
63
    public function isTokenValid(CsrfToken $token): bool
64
    {
65
        if (!$this->storage->has($token->tokenId())) {
66
            return false;
67
        }
68
69
        return $token->value() === $this->storage->get($token->tokenId());
70
    }
71
}
72