Completed
Push — master ( 32a55a...fb9711 )
by Mitchel
02:18
created

FileTokenStorage::save()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
dl 12
loc 12
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
3
namespace Bunq\Token\Storage;
4
5
use Bunq\Token\DefaultToken;
6
use Bunq\Token\Token;
7
use Bunq\Token\TokenType;
8
9 View Code Duplication
final class FileTokenStorage implements TokenStorage
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
10
{
11
    /**
12
     * @var string
13
     */
14
    private $path;
15
16
    /**
17
     * @var array
18
     */
19
    private $cache = [];
20
21
    /**
22
     * @param string $path
23
     */
24
    public function __construct($path)
25
    {
26
        $this->path = (string)$path . '/tokens';
27
    }
28
29
    /**
30
     * @inheritdoc
31
     */
32
    public function load(TokenType $type)
33
    {
34
        if (!file_exists($this->path . '/' . $type->toString())) {
35
            throw new TokenNotFoundException($type, $this->path);
36
        }
37
38
        $token = $this->loadToken($type);
39
40
        return DefaultToken::fromString($token);
41
    }
42
43
    /**
44
     * @inheritdoc
45
     */
46
    public function save(Token $token, TokenType $type)
47
    {
48
        $token = trim($token->toString());
49
50
        if (!file_exists($this->path)) {
51
            mkdir($this->path);
52
        }
53
54
        file_put_contents($this->path . '/' . $type->toString(), $token);
55
56
        $this->cache[$type->toString()] = $token;
57
    }
58
59
    /**
60
     * @param TokenType $type
61
     *
62
     * @return string
63
     *
64
     * @throws TokenNotFoundException
65
     */
66
    private function loadToken(TokenType $type)
67
    {
68
        // take from cache, filesystems are slow
69
        if (isset($this->cache[$type->toString()])) {
70
            return $this->cache[$type->toString()];
71
        }
72
73
        $token = trim(file_get_contents($this->path . '/' . $type->toString()));
74
75
        if (!$token) {
76
            throw new TokenNotFoundException($type, $this->path);
77
        }
78
79
        // save the result in the cache
80
        $this->cache[$type->toString()] = $token;
81
82
        return $token;
83
    }
84
}
85