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

FileStorage   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 35
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A save() 0 4 1
A load() 0 9 2
A destroy() 0 4 1
A buildPath() 0 4 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