Completed
Pull Request — master (#30)
by Rudolph
04:05 queued 53s
created

MemoryStorage::save()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace PSR7Sessions\Storage\Adapter;
4
5
use PSR7Sessions\Storage\Id\SessionIdInterface;
6
use PSR7Sessions\Storage\Session\StorableSession;
7
use PSR7Sessions\Storage\Session\StorableSessionInterface;
8
use PSR7Sessions\Storageless\Session\DefaultSessionData;
9
10
class MemoryStorage implements StorageInterface
11
{
12
    /** @var array */
13
    private $sessions = [];
14
15
    public function save(StorableSessionInterface $session)
16
    {
17
        $this->sessions[(string)$session->getId()] = $session->jsonSerialize();
18
    }
19
20
    public function load(SessionIdInterface $id):StorableSessionInterface
21
    {
22
        $stringId = (string)$id;
23
        if (!$this->has($stringId)) {
24
            return StorableSession::fromId(DefaultSessionData::newEmptySession(), $this, $id);
25
        }
26
        $wrappedSession = DefaultSessionData::fromTokenData($this->sessions[$stringId]);
27
        return new StorableSession($wrappedSession, $this);
28
    }
29
30
    public function destroy(SessionIdInterface $id)
31
    {
32
        $stringId = (string)$id;
33
        if (!$this->has($stringId)) {
34
            return;
35
        }
36
        unset($this->sessions[$stringId]);
37
    }
38
39
    private function has(string $id):bool
40
    {
41
        return array_key_exists($id, $this->sessions);
42
    }
43
}
44