Completed
Pull Request — master (#20)
by Alexander
01:34
created

Session   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 79
rs 10
c 0
b 0
f 0
wmc 13

7 Methods

Rating   Name   Duplication   Size   Complexity  
A unset() 0 3 1
A get() 0 10 3
A destroy() 0 10 2
A check() 0 3 1
A active() 0 3 1
A startIfNotStarted() 0 4 2
A set() 0 9 3
1
<?php
2
3
namespace alkemann\h2l;
4
5
/**
6
 * Class Session implementation that access $_SESSION directly
7
 *
8
 * @codeCoverageIgnore
9
 * @package alkemann\h2l
10
 */
11
class Session implements interfaces\Session
12
{
13
    public function startIfNotStarted(): void
14
    {
15
        if ($this->active() === false) {
16
            session_start();
17
        }
18
    }
19
20
    /**
21
     * @param string $key
22
     * @return mixed|null
23
     */
24
    public function get(string $key)
25
    {
26
        $this->startIfNotStarted();
27
        if (isset($_SESSION[$key])) {
28
            return $_SESSION[$key];
29
        }
30
        if (strpos($key, '.') !== false) {
31
            return Util::getFromArrayByKey($key, $_SESSION);
32
        }
33
        return null;
34
    }
35
36
    /**
37
     * @param string $key
38
     * @param $value
39
     * @throws \Error if trying to set with dot notation
40
     */
41
    public function set(string $key, $value): void
42
    {
43
        if ($this->active() === false) {
44
            session_start();
45
        }
46
        if (strpos($key, '.') !== false) {
47
            throw new \Error("Dot notation setting of Session values not implemented yet");
48
        }
49
        $_SESSION[$key] = $value;
50
    }
51
52
    /**
53
     * @param string $key
54
     */
55
    public function unset(string $key): void
56
    {
57
        unset($_SESSION[$key]);
58
    }
59
60
    /**
61
     * @return bool
62
     */
63
    private function active(): bool
64
    {
65
        return session_status() === \PHP_SESSION_ACTIVE;
66
    }
67
68
    /**
69
     * @return bool
70
     */
71
    public function destroy(): bool
72
    {
73
        session_destroy();
74
        if ($this->active()) {
75
            session_destroy();
76
            unset($_SESSION);
77
78
            return $this->active() === false;
79
        }
80
        return false;
81
    }
82
83
    /**
84
     * @param string $key
85
     * @return bool
86
     */
87
    public function check(string $key): bool
88
    {
89
        return isset($_SESSION[$key]);
90
    }
91
}
92