SessionObject   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 20
c 1
b 0
f 0
dl 0
loc 70
ccs 22
cts 22
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A persist() 0 7 1
A getInfo() 0 3 1
A forRequest() 0 12 2
A clear() 0 4 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\Auth\Session;
6
7
use ArrayAccess;
8
use DateTimeInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
11
/**
12
 * Use OOP abstracted sessions to store auth session info.
13
 */
14
class SessionObject implements SessionInterface
15
{
16
    use GetInfoTrait;
17
18
    protected string $key;
19
20
    /** @var ArrayAccess<string,mixed> */
21
    protected ArrayAccess $session;
22
23
    /**
24
     * Service constructor.
25
     *
26
     * @param ArrayAccess<string,mixed> $session
27
     * @param string                     $key
28
     */
29 9
    public function __construct(ArrayAccess $session, string $key = 'auth')
30
    {
31 9
        $this->session = $session;
32 9
        $this->key = $key;
33
    }
34
35
    /**
36
     * Use the `session` attribute if it's an object that implements ArrayAccess.
37
     *
38
     * @param ServerRequestInterface $request
39
     * @return self
40
     */
41 4
    public function forRequest(ServerRequestInterface $request): self
42
    {
43 4
        $session = $request->getAttribute('session');
44
45 4
        if (!$session instanceof ArrayAccess) {
46 1
            return $this;
47
        }
48
49 3
        $copy = clone $this;
50 3
        $copy->session = $session;
51
52 3
        return $copy;
53
    }
54
55
56
    /**
57
     * @inheritDoc
58
     */
59 5
    public function getInfo(): array
60
    {
61 5
        return $this->getInfoFromData($this->session[$this->key] ?? []);
62
    }
63
64
    /**
65
     * @inheritDoc
66
     */
67 2
    public function persist(mixed $userId, mixed $contextId, ?string $checksum, ?DateTimeInterface $timestamp): void
68
    {
69 2
        $this->session[$this->key] = [
70 2
            'user' => $userId,
71 2
            'context' => $contextId,
72 2
            'checksum' => $checksum,
73 2
            'timestamp' => $timestamp?->getTimestamp(),
74 2
        ];
75
    }
76
77
    /**
78
     * Remove auth information from session.
79
     */
80 2
    public function clear(): void
81
    {
82 2
        if (isset($this->session[$this->key])) {
83 1
            unset($this->session[$this->key]);
84
        }
85
    }
86
}
87