Failed Conditions
Push — master ( 2436f4...03b798 )
by Arnold
02:53
created

PhpSession   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 6
eloc 15
dl 0
loc 66
ccs 20
cts 20
cp 1
rs 10
c 2
b 1
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A clear() 0 5 1
A assertSessionStarted() 0 4 2
A __construct() 0 3 1
A persist() 0 5 1
A getInfo() 0 10 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\Auth\Session;
6
7
/**
8
 * Use PHP sessions to store auth session info.
9
 */
10
class PhpSession implements SessionInterface
11
{
12
    protected string $key;
13
14
    /**
15
     * Service constructor.
16
     *
17
     * @param string $key
18
     */
19 7
    public function __construct(string $key = 'auth')
20
    {
21 7
        $this->key = $key;
22 7
    }
23
24
    /**
25
     * Assert that there is an active session.
26
     *
27
     * @throws \RuntimeException if there is no active session
28
     */
29 7
    protected function assertSessionStarted(): void
30
    {
31 7
        if (session_status() !== \PHP_SESSION_ACTIVE) {
32 3
            throw new \RuntimeException("Unable to use session for auth info: Session not started");
33
        }
34 4
    }
35
36
    /**
37
     * Get auth information from session.
38
     *
39
     * @return array{uid:mixed,context:mixed,checksum:string|null}
40
     */
41 3
    public function getInfo(): array
42
    {
43 3
        $this->assertSessionStarted();
44
45 2
        $data = $_SESSION[$this->key] ?? [];
46
47
        return [
48 2
            'uid' => $data['uid'] ?? null,
49 2
            'context' => $data['context'] ?? null,
50 2
            'checksum' => $data['checksum'] ?? null,
51
        ];
52
    }
53
54
    /**
55
     * Persist auth information to session.
56
     *
57
     * @param string|int  $uid
58
     * @param mixed       $context
59
     * @param string|null $checksum
60
     */
61 2
    public function persist($uid, $context, ?string $checksum): void
62
    {
63 2
        $this->assertSessionStarted();
64
65 1
        $_SESSION[$this->key] = compact('uid', 'context', 'checksum');
66 1
    }
67
68
    /**
69
     * Remove auth information from session.
70
     */
71 2
    public function clear(): void
72
    {
73 2
        $this->assertSessionStarted();
74
75 1
        unset($_SESSION[$this->key]);
76 1
    }
77
}
78