Passed
Push — master ( 1ae96b...301b02 )
by Jelmer
03:29
created

GenericSession::processFlashData()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 15
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 4
nop 1
crap 20
1
<?php declare(strict_types = 1);
2
3
namespace jschreuder\Middle\Session;
4
5
class GenericSession implements SessionInterface
6
{
7
    const FLASH_DATA_KEY_PREFIX = '_flash_data.';
8
    const FLASH_DATA_META_KEY = '_flash_data_keys';
9
10
    /** @var  array */
11
    private $sessionData;
12
13
    /** @var  bool */
14
    private $changed = false;
15
16
    public function __construct(array $sessionData = [])
17
    {
18
        $this->sessionData = $this->processFlashData($sessionData);
19
    }
20
21
    private function processFlashData(array $sessionData) : array
22
    {
23
        if (!isset($sessionData[self::FLASH_DATA_META_KEY])) {
24
            return $sessionData;
25
        }
26
27
        foreach ($sessionData[self::FLASH_DATA_META_KEY] as $key => $hops) {
28
            if ($hops <= 0) {
29
                unset($sessionData[self::FLASH_DATA_META_KEY][$key]);
30
                unset($sessionData[self::FLASH_DATA_KEY_PREFIX . $key]);
31
            } else {
32
                $sessionData[self::FLASH_DATA_META_KEY][$key]--;
33
            }
34
        }
35
        return $sessionData;
36
    }
37
38
    /** @return  void */
39
    private function markFlashKey(string $key)
40
    {
41
        $this->sessionData[self::FLASH_DATA_META_KEY][$key] = 1;
42
    }
43
44
    public function has(string $key) : bool
45
    {
46
        return isset($this->sessionData[$key]);
47
    }
48
49
    public function get(string $key)
50
    {
51
        return $this->sessionData[$key] ?? null;
52
    }
53
54
    public function set(string $key, $value)
55
    {
56
        $this->changed = true;
57
        $this->sessionData[self::FLASH_DATA_KEY_PREFIX . $key] = $value;
58
    }
59
60
    public function getFlash(string $key)
61
    {
62
        return $this->sessionData[self::FLASH_DATA_KEY_PREFIX . $key] ?? null;
63
    }
64
65
    public function setFlash(string $key, $value)
66
    {
67
        $this->changed = true;
68
        $this->markFlashKey($key);
69
        $this->sessionData[$key] = $value;
70
    }
71
72
    public function destroy()
73
    {
74
        $this->sessionData = [];
75
    }
76
77
    public function rotateId()
78
    {
79
        // These sessions don't have an ID
80
    }
81
82
    public function isEmpty() : bool
83
    {
84
        return count($this->sessionData) === 0;
85
    }
86
87
    public function hasChanged() : bool
88
    {
89
        return $this->changed;
90
    }
91
92
    public function toArray() : array
93
    {
94
        return $this->sessionData;
95
    }
96
}
97