Passed
Push — master ( de36b3...61fcdc )
by Rustam
09:16
created

FileStorage   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 146
Duplicated Lines 0 %

Test Coverage

Coverage 77.78%

Importance

Changes 6
Bugs 0 Features 0
Metric Value
eloc 63
c 6
b 0
f 0
dl 0
loc 146
ccs 56
cts 72
cp 0.7778
rs 10
wmc 18

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A addCollector() 0 3 1
A setHistorySize() 0 3 1
A reindexObjects() 0 8 2
A clear() 0 3 1
A getData() 0 8 2
A read() 0 15 2
A flush() 0 18 1
A collectIndexData() 0 11 3
A gc() 0 18 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Debug\Storage;
6
7
use League\Flysystem\FilesystemException;
8
use Yiisoft\Aliases\Aliases;
9
use Yiisoft\Json\Json;
10
use Yiisoft\Yii\Debug\Collector\CollectorInterface;
11
use Yiisoft\Yii\Debug\Collector\IndexCollectorInterface;
12
use Yiisoft\Yii\Debug\DebuggerIdGenerator;
13
use Yiisoft\Yii\Debug\Dumper;
14
use Yiisoft\Yii\Filesystem\FilesystemInterface;
15
16
use function array_merge;
17
use function array_slice;
18
use function count;
19
use function dirname;
20
use function filemtime;
21
use function get_class;
22
use function glob;
23
use function strlen;
24
use function substr;
25
use function uasort;
26
27
final class FileStorage implements StorageInterface
28
{
29
    /**
30
     * @var CollectorInterface[]
31
     */
32
    private array $collectors = [];
33
34
    private string $path;
35
36
    private int $historySize = 50;
37
38
    private DebuggerIdGenerator $idGenerator;
39
40
    private FilesystemInterface $filesystem;
41
42
    private Aliases $aliases;
43
44 40
    public function __construct(
45
        string $path,
46
        FilesystemInterface $filesystem,
47
        DebuggerIdGenerator $idGenerator,
48
        Aliases $aliases
49
    ) {
50 40
        $this->path = $path;
51 40
        $this->filesystem = $filesystem;
52 40
        $this->idGenerator = $idGenerator;
53 40
        $this->aliases = $aliases;
54 40
    }
55
56 40
    public function addCollector(CollectorInterface $collector): void
57
    {
58 40
        $this->collectors[get_class($collector)] = $collector;
59 40
    }
60
61 8
    public function setHistorySize(int $historySize): void
62
    {
63 8
        $this->historySize = $historySize;
64 8
    }
65
66 16
    public function read($type = self::TYPE_INDEX): array
67
    {
68 16
        clearstatcache();
69 16
        $data = [];
70 16
        $path = $this->aliases->get($this->path);
71 16
        $dataFiles = glob($path . '/**/**/' . $type . '.json', GLOB_NOSORT);
72 16
        uasort($dataFiles, static fn ($a, $b) => filemtime($a) <=> filemtime($b));
73
74 16
        foreach ($dataFiles as $file) {
75
            $dir = dirname($file);
76
            $id = substr($dir, strlen(dirname($file, 2)) + 1);
77
            $data[$id] = Json::decode(file_get_contents($file));
78
        }
79
80 16
        return $data;
81
    }
82
83 32
    public function flush(): void
84
    {
85 32
        $basePath = $this->path . '/' . date('Y-m-d') . '/' . $this->idGenerator->getId() . '/';
86
        try {
87 32
            $dumper = Dumper::create($this->getData());
88 32
            $jsonData = $dumper->asJson();
89 32
            $this->filesystem->write($basePath . self::TYPE_DATA . '.json', $jsonData);
90
91 32
            $jsonObjects = json_decode($dumper->asJsonObjectsMap(), true);
92 32
            $jsonObjects = $this->reindexObjects($jsonObjects);
93 32
            $this->filesystem->write($basePath . self::TYPE_OBJECTS . '.json', Dumper::create($jsonObjects)->asJson());
94
95 32
            $indexData = Dumper::create($this->collectIndexData())->asJson();
96 32
            $this->filesystem->write($basePath . self::TYPE_INDEX . '.json', $indexData);
97
98 32
            $this->gc();
99 32
        } finally {
100 32
            $this->collectors = [];
101
        }
102 32
    }
103
104 40
    public function getData(): array
105
    {
106 40
        $data = [];
107 40
        foreach ($this->collectors as $collector) {
108 40
            $data[get_class($collector)] = $collector->getCollected();
109
        }
110
111 40
        return $data;
112
    }
113
114 8
    public function clear(): void
115
    {
116 8
        $this->filesystem->deleteDirectory($this->path);
117 8
    }
118
119
    /**
120
     * Collects summary data of current request.
121
     *
122
     * @return array
123
     */
124 32
    private function collectIndexData(): array
125
    {
126 32
        $indexData = ['id' => $this->idGenerator->getId()];
127
128 32
        foreach ($this->collectors as $collector) {
129 32
            if ($collector instanceof IndexCollectorInterface) {
130
                $indexData = array_merge($indexData, $collector->getIndexData());
131
            }
132
        }
133
134 32
        return $indexData;
135
    }
136
137
    /**
138
     * Removes obsolete data files
139
     *
140
     * @throws FilesystemException
141
     */
142 32
    private function gc(): void
143
    {
144 32
        $indexFiles = glob($this->aliases->get($this->path) . '/**/**/index.json', GLOB_NOSORT);
145 32
        if (count($indexFiles) >= $this->historySize + 1) {
146
            uasort($indexFiles, static fn ($a, $b) => filemtime($b) <=> filemtime($a));
147
            $excessFiles = array_slice($indexFiles, $this->historySize);
148
            foreach ($excessFiles as $file) {
149
                $path1 = dirname($file);
150
                $path2 = dirname($file, 2);
151
                $path3 = dirname($file, 3);
152
                $resource = substr($path1, strlen($path3));
153
                $this->filesystem->deleteDirectory($this->path . $resource);
154
155
                // Clean empty group directories
156
                $group = substr($path2, strlen($path3));
157
                $list = $this->filesystem->listContents($this->path . $group);
158
                if (empty($list->toArray())) {
159
                    $this->filesystem->deleteDirectory($this->path . $group);
160
                }
161
            }
162
        }
163 32
    }
164
165 32
    private function reindexObjects(array $objectsAsArraysCollection): array
166
    {
167 32
        $result = [];
168 32
        foreach ($objectsAsArraysCollection as $objectAsArray) {
169 4
            $result = array_merge($result, $objectAsArray);
170
        }
171
172 32
        return $result;
173
    }
174
}
175