SnapshotService::getSnapshots()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php
2
3
namespace Spiral\Snapshotter\FileHandler\Services;
4
5
use Spiral\Core\Service;
6
use Spiral\Debug\Configs\SnapshotConfig;
7
use Spiral\Files\FileManager;
8
use Spiral\Snapshotter\FileHandler\Entities\FileSnapshot;
9
use Vvval\Spiral\PaginableArray;
10
11
class SnapshotService extends Service
12
{
13
    /** @var SnapshotConfig */
14
    private $config;
15
16
    /** @var FileManager */
17
    private $files;
18
19
    /**
20
     * SnapshotService constructor.
21
     *
22
     * @param SnapshotConfig $config
23
     * @param FileManager    $files
24
     */
25
    public function __construct(SnapshotConfig $config, FileManager $files)
26
    {
27
        $this->config = $config;
28
        $this->files = $files;
29
    }
30
31
    /**
32
     * Get snapshots.
33
     *
34
     * @return PaginableArray
35
     */
36
    public function getSnapshots(): PaginableArray
37
    {
38
        $order = [];
39
        $snapshots = [];
40
41
        if (!$this->files->exists($this->config->reportingDirectory())) {
42
            return new PaginableArray();
43
        }
44
45
        foreach ($this->files->getFiles($this->config->reportingDirectory(), '*.html') as $file) {
46
            $snapshots[] = new FileSnapshot($file);
47
            $order[] = $this->files->time($file);
48
        }
49
50
        array_multisort($order, SORT_DESC, $snapshots);
51
52
        return new PaginableArray($snapshots);
53
    }
54
55
    /**
56
     * @param string $filename
57
     * @return null|FileSnapshot
58
     */
59
    public function getSnapshot(string $filename)
60
    {
61
        if (!$this->exists($filename)) {
62
            return null;
63
        }
64
65
        return new FileSnapshot($this->config->reportingDirectory() . $filename);
66
    }
67
68
    /**
69
     *
70
     */
71
    public function deleteSnapshots()
72
    {
73
        foreach ($this->files->getFiles($this->config->reportingDirectory(), '*.html') as $file) {
74
            $this->files->delete($file);
75
        }
76
    }
77
78
    /**
79
     * @param FileSnapshot $filename
80
     */
81
    public function deleteSnapshot(FileSnapshot $filename)
82
    {
83
        $this->files->delete($filename->path());
84
    }
85
86
    /**
87
     * @param string $filename
88
     * @return bool
89
     */
90
    public function exists(string $filename): bool
91
    {
92
        return $this->files->exists($this->config->reportingDirectory() . $filename);
93
    }
94
95
    /**
96
     * @param FileSnapshot $snapshot
97
     * @return string
98
     */
99
    public function read(FileSnapshot $snapshot): string
100
    {
101
        return $this->files->read($snapshot->path());
102
    }
103
}