PhpSession::set()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 5
rs 10
ccs 0
cts 3
cp 0
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DMK\MKSamlAuth\Session;
6
7
use TYPO3\CMS\Core\SingletonInterface;
8
9
class PhpSession implements SingletonInterface
10
{
11
    private const DEFAULT_SESSION_OPTIONS = [
12
        'name' => 'saml_auth',
13
        'cookie_secure' => true,
14
        'cookie_httponly' => true,
15
        // 60 seconds should suffice to fill the login form
16
        'cookie_lifetime' => 60,
17
        // Session fixation protection:
18
        'use_strict_mode' => true,
19
    ];
20
21
    private const SESSION_KEY = 'DMK_SESSION';
22
23
    /**
24
     * @var bool
25
     */
26
    private $started = false;
27
28
    /**
29
     * Starts the new session.
30
     */
31
    public function start(): void
32
    {
33
        if ($this->started) {
34
            return;
35
        }
36
37
        session_start(self::DEFAULT_SESSION_OPTIONS);
38
39
        if (false === isset($_SESSION[self::SESSION_KEY])) {
40
            // Additional (in case strict mode fails for some reason) session fixation protection
41
            session_regenerate_id(true);
42
            $_SESSION = [];
43
            $_SESSION[self::SESSION_KEY]['started'] = true;
44
        }
45
46
        $this->started = true;
47
    }
48
49
    /**
50
     * Returns the session id.
51
     */
52
    public function getId(): string
53
    {
54
        $this->start();
55
56
        return session_id();
57
    }
58
59
    /**
60
     * Closes the session and write it down.
61
     */
62
    public function close(): void
63
    {
64
        $this->started = false;
65
        session_write_close();
66
    }
67
68
    /**
69
     * Sets a new value to the session.
70
     *
71
     * @param mixed $value
72
     */
73
    public function set(string $key, $value): void
74
    {
75
        $this->start();
76
77
        $_SESSION[self::SESSION_KEY][$key] = $value;
78
    }
79
80
    /**
81
     * Gets a value from the storage, if the key could not be found
82
     * it will return null.
83
     *
84
     * @return mixed|null
85
     */
86
    public function get(string $key)
87
    {
88
        $this->start();
89
90
        if (\array_key_exists($key, $_SESSION[self::SESSION_KEY])) {
91
            return null;
92
        }
93
94
        return $_SESSION[self::SESSION_KEY][$key];
95
    }
96
}
97