SessionObject::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
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 4
ccs 3
cts 3
cp 1
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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