Completed
Push — master ( fd92ed...e2f694 )
by Freek
10:21
created

Snapshot::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Spatie\DbSnapshots;
4
5
use Carbon\Carbon;
6
use Illuminate\Filesystem\FilesystemAdapter as Disk;
7
use Illuminate\Support\Facades\DB;
8
use Spatie\DbSnapshots\Events\DeletedSnapshot;
9
use Spatie\DbSnapshots\Events\DeletingSnapshot;
10
use Spatie\DbSnapshots\Events\LoadedSnapshot;
11
use Spatie\DbSnapshots\Events\LoadingSnapshot;
12
13
class Snapshot
14
{
15
    public Disk $disk;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
16
17
    public string $fileName;
18
19
    public string $name;
20
21
    public ?string $compressionExtension = null;
22
23
    public function __construct(Disk $disk, string $fileName)
24
    {
25
        $this->disk = $disk;
26
27
        $this->fileName = $fileName;
28
29
        $pathinfo = pathinfo($fileName);
30
31
        if ($pathinfo['extension'] === 'gz') {
32
            $this->compressionExtension = $pathinfo['extension'];
33
            $fileName = $pathinfo['filename'];
34
        }
35
36
        $this->name = pathinfo($fileName, PATHINFO_FILENAME);
37
    }
38
39
    public function load(string $connectionName = null)
40
    {
41
        event(new LoadingSnapshot($this));
42
43
        if ($connectionName !== null) {
44
            DB::setDefaultConnection($connectionName);
45
        }
46
47
        $this->dropAllCurrentTables();
48
49
        $dbDumpContents = $this->disk->get($this->fileName);
50
51
        if ($this->compressionExtension === 'gz') {
52
            $dbDumpContents = gzdecode($dbDumpContents);
53
        }
54
55
        DB::connection($connectionName)->unprepared($dbDumpContents);
56
57
        event(new LoadedSnapshot($this));
58
    }
59
60
    public function delete()
61
    {
62
        event(new DeletingSnapshot($this));
63
64
        $this->disk->delete($this->fileName);
65
66
        event(new DeletedSnapshot($this->fileName, $this->disk));
67
    }
68
69
    public function size(): int
70
    {
71
        return $this->disk->size($this->fileName);
72
    }
73
74
    public function createdAt(): Carbon
75
    {
76
        return Carbon::createFromTimestamp($this->disk->lastModified($this->fileName));
77
    }
78
79
    protected function dropAllCurrentTables()
80
    {
81
        DB::connection(DB::getDefaultConnection())
82
            ->getSchemaBuilder()
83
            ->dropAllTables();
84
85
        DB::reconnect();
86
    }
87
}
88