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

FileStorage::load()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace PSR7Sessions\Storage\Adapter;
6
7
use PSR7Sessions\Storage\Id\SessionIdInterface;
8
use PSR7Sessions\Storage\Session\StorableSession;
9
use PSR7Sessions\Storage\Session\StorableSessionInterface;
10
use PSR7Sessions\Storageless\Session\DefaultSessionData;
11
12
class FileStorage implements StorageInterface
13
{
14
    /** @var string */
15
    private $directory;
16
17
    public function __construct(string $directory)
18
    {
19
        $this->directory = $directory;
20
    }
21
22
    public function save(StorableSessionInterface $session)
23
    {
24
        file_put_contents($this->buildPath($session->getId()), json_encode($session));
25
    }
26
27
    public function load(SessionIdInterface $id):StorableSessionInterface
28
    {
29
        $path = $this->buildPath($id);
30
        if (!file_exists($path)) {
31
            return new StorableSession(DefaultSessionData::newEmptySession(), $this);
32
        }
33
        $json = file_get_contents($path);
34
        return StorableSession::fromId(DefaultSessionData::fromTokenData(json_decode($json, true)), $this, $id);
35
    }
36
37
    public function destroy(SessionIdInterface $id)
38
    {
39
        unlink($this->buildPath($id));
40
    }
41
42
    private function buildPath(SessionIdInterface $id) : string
43
    {
44
        return $this->directory . '/' . $id;
45
    }
46
}
47