Completed
Push — master ( 7640f5...45768c )
by BENOIT
05:12
created

JsonFileSecretStorage::getKeys()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace BenTools\Shh\SecretStorage;
4
5
use BenTools\Shh\Shh;
6
7
final class JsonFileSecretStorage implements SecretStorageInterface
8
{
9
    /**
10
     * @var Shh
11
     */
12
    private $shh;
13
14
    /**
15
     * @var string
16
     */
17
    private $secretsFile;
18
19
    public function __construct(Shh $shh, string $secretsFile)
20
    {
21
        $this->shh = $shh;
22
        $this->secretsFile = $secretsFile;
23
    }
24
25
    /**
26
     * @return array
27
     */
28
    private function open(): array
29
    {
30
        if (false === \file_exists($this->secretsFile)) {
31
            $secrets = [];
32
        } else {
33
            $content = \file_get_contents($this->secretsFile);
34
            $secrets = '' === $content ? [] : \json_decode($content, true);
35
            if (\JSON_ERROR_NONE !== \json_last_error()) {
36
                throw new \RuntimeException('json_decode error: '.\json_last_error_msg());
37
            }
38
        }
39
40
        return $secrets;
41
    }
42
43
    /**
44
     * @inheritDoc
45
     */
46
    public function store(string $key, string $value, bool $encrypt = true): void
47
    {
48
        $secrets = $this->open();
49
50
        if (true === $encrypt) {
51
            $value = $this->shh->encrypt($value);
52
        }
53
54
        if (false === \file_put_contents($this->secretsFile, \json_encode(\array_replace($secrets, [$key => $value]), \JSON_PRETTY_PRINT))) {
55
            throw new \RuntimeException(\sprintf('Could not write to %s.', $this->secretsFile));
56
        }
57
58
        if (\JSON_ERROR_NONE !== \json_last_error()) {
59
            throw new \RuntimeException('json_encode error: '.\json_last_error_msg());
60
        }
61
    }
62
63
    public function has(string $key): bool
64
    {
65
        return \in_array($key, $this->getKeys(), true);
66
    }
67
68
    /**
69
     * @inheritDoc
70
     */
71
    public function get(string $key, bool $decrypt = true): ?string
72
    {
73
        if (false === $decrypt) {
74
            return $this->open()[$key] ?? null;
75
        }
76
77
        $raw = $this->get($key, false);
78
79
        return null !== $raw ? $this->shh->decrypt($raw) : null;
80
    }
81
82
    /**
83
     * @inheritDoc
84
     */
85
    public function getKeys(): iterable
86
    {
87
        return \array_keys($this->open());
88
    }
89
}
90