PhpSession::clear()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\Auth\Session;
6
7
use DateTimeInterface;
8
use RuntimeException;
9
use const PHP_SESSION_ACTIVE;
10
11
/**
12
 * Use PHP sessions to store auth session info.
13
 */
14
class PhpSession implements SessionInterface
15
{
16
    use GetInfoTrait;
17
18
    protected string $key;
19
20
    /**
21
     * Service constructor.
22
     *
23
     * @param string $key
24
     */
25 9
    public function __construct(string $key = 'auth')
26
    {
27 9
        $this->key = $key;
28
    }
29
30
    /**
31
     * Assert that there is an active session.
32
     *
33
     * @throws RuntimeException if there is no active session
34
     */
35 9
    protected function assertSessionStarted(): void
36
    {
37 9
        if (session_status() !== PHP_SESSION_ACTIVE) {
38 3
            throw new RuntimeException("Unable to use session for auth info: Session not started");
39
        }
40
    }
41
42
    /**
43
     * @inheritDoc
44
     */
45 5
    public function getInfo(): array
46
    {
47 5
        $this->assertSessionStarted();
48
49 4
        return $this->getInfoFromData($_SESSION[$this->key] ?? []);
50
    }
51
52
    /**
53
     * @inheritDoc
54
     */
55 2
    public function persist(mixed $userId, mixed $contextId, ?string $checksum, ?DateTimeInterface $timestamp): void
56
    {
57 2
        $this->assertSessionStarted();
58
59 1
        $_SESSION[$this->key] = [
60 1
            'user' => $userId,
61 1
            'context' => $contextId,
62 1
            'checksum' => $checksum,
63 1
            'timestamp' => $timestamp?->getTimestamp(),
64 1
        ];
65
    }
66
67
    /**
68
     * @inheritDoc
69
     */
70 2
    public function clear(): void
71
    {
72 2
        $this->assertSessionStarted();
73
74 1
        unset($_SESSION[$this->key]);
75
    }
76
}
77