Passed
Push — master ( 81d966...4376d2 )
by butschster
23:34 queued 15s
created

StorageSnapshot::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 7
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 5
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Snapshots;
6
7
use Spiral\Exceptions\ExceptionRendererInterface;
8
use Spiral\Exceptions\Verbosity;
9
use Spiral\Storage\StorageInterface;
10
11
class StorageSnapshot
12
{
13 4
    public function __construct(
14
        protected readonly string $bucket,
15
        protected readonly StorageInterface $storage,
16
        protected readonly Verbosity $verbosity,
17
        protected readonly ExceptionRendererInterface $renderer,
18
        protected readonly ?string $directory = null
19
    ) {
20 4
    }
21
22 2
    public function create(\Throwable $e): SnapshotInterface
23
    {
24 2
        $snapshot = new Snapshot($this->getID($e), $e);
25
26 2
        $this->saveSnapshot($snapshot);
27
28 2
        return $snapshot;
29
    }
30
31 2
    protected function saveSnapshot(SnapshotInterface $snapshot): void
32
    {
33 2
        $filename = $this->getFilename($snapshot, new \DateTime());
34
35 2
        $this->storage
36 2
            ->bucket($this->bucket)
37 2
            ->create($this->directory !== null ? $this->directory . DIRECTORY_SEPARATOR . $filename : $filename)
38 2
            ->write($this->renderer->render($snapshot->getException(), $this->verbosity));
39
    }
40
41
    /**
42
     * @throws \Exception
43
     */
44 2
    protected function getFilename(SnapshotInterface $snapshot, \DateTimeInterface $time): string
45
    {
46 2
        return \sprintf(
47 2
            '%s-%s.txt',
48 2
            $time->format('d.m.Y-Hi.s'),
49 2
            (new \ReflectionClass($snapshot->getException()))->getShortName()
50 2
        );
51
    }
52
53 2
    protected function getID(\Throwable $e): string
54
    {
55 2
        return \md5(\implode('|', [$e->getMessage(), $e->getFile(), $e->getLine()]));
56
    }
57
}
58