JsonStorage   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 10
c 1
b 0
f 0
dl 0
loc 31
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A hasData() 0 3 1
A read() 0 10 2
A write() 0 5 1
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the composer-link plugin.
7
 *
8
 * Copyright (c) 2021-2022 Sander Visser <[email protected]>.
9
 *
10
 * For the full copyright and license information, please view the LICENSE.md
11
 * file that was distributed with this source code.
12
 *
13
 * @link https://github.com/SanderSander/composer-link
14
 */
15
16
namespace ComposerLink\Repository;
17
18
use RuntimeException;
19
20
class JsonStorage implements StorageInterface
21
{
22
    protected string $file;
23
24
    public function __construct(string $file)
25
    {
26
        $this->file = $file;
27
    }
28
29
    public function write(array $data): void
30
    {
31
        /** @var string $json */
32
        $json = json_encode($data);
33
        file_put_contents($this->file, $json);
34
    }
35
36
    public function read(): array
37
    {
38
        if (!$this->hasData()) {
39
            throw new RuntimeException('Cannot read data, no data stored.');
40
        }
41
42
        /** @var string $data */
43
        $data = file_get_contents($this->file);
44
45
        return json_decode($data, true);
46
    }
47
48
    public function hasData(): bool
49
    {
50
        return file_exists($this->file);
51
    }
52
}
53