Completed
Push — master ( 901a4d...e089b7 )
by Freek
02:01
created

SnapshotFactory::createDump()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 3
1
<?php
2
3
namespace Spatie\DbSnapshots;
4
5
use Spatie\DbDumper\DbDumper;
6
use Illuminate\Contracts\Filesystem\Factory;
7
use Illuminate\Filesystem\FilesystemAdapter;
8
use Spatie\DbSnapshots\Events\CreatedSnapshot;
9
use Spatie\DbSnapshots\Events\CreatingSnapshot;
10
use Spatie\TemporaryDirectory\TemporaryDirectory;
11
use Spatie\DbSnapshots\Exceptions\CannotCreateDisk;
12
13
class SnapshotFactory
14
{
15
    /** @var \Spatie\DbSnapshots\DbDumperFactory */
16
    protected $dumperFactory;
17
18
    /** @var \Illuminate\Contracts\Filesystem\Factory */
19
    protected $filesystemFactory;
20
21
    public function __construct(DbDumperFactory $dumperFactory, Factory $filesystemFactory)
22
    {
23
        $this->dumperFactory = $dumperFactory;
24
25
        $this->filesystemFactory = $filesystemFactory;
26
    }
27
28
    public function create(string $snapshotName, string $diskName, string $connectionName): Snapshot
29
    {
30
        $disk = $this->getDisk($diskName);
31
32
        $fileName = $snapshotName.'.sql';
33
34
        event(new CreatingSnapshot(
35
            $fileName,
36
            $disk,
37
            $connectionName
38
        ));
39
40
        $this->createDump($connectionName, $fileName, $disk);
41
42
        $snapshot = new Snapshot($disk, $fileName);
43
44
        event(new CreatedSnapshot($snapshot));
45
46
        return $snapshot;
47
    }
48
49
    protected function getDisk(string $diskName): FilesystemAdapter
50
    {
51
        if (is_null(config("filesystems.disks.{$diskName}"))) {
52
            throw CannotCreateDisk::diskNotDefined($diskName);
53
        }
54
55
        return $this->filesystemFactory->disk($diskName);
56
    }
57
58
    protected function getDbDumper(string $connectionName): DbDumper
59
    {
60
        $factory = $this->dumperFactory;
61
62
        return $factory::createForConnection($connectionName);
63
    }
64
65
    protected function createDump(string $connectionName, string $fileName, FilesystemAdapter $disk)
66
    {
67
        $directory = (new TemporaryDirectory(config('db-snapshots.temporary_directory_path')))->create();
68
69
        $dumpPath = $directory->path($fileName);
70
71
        $this->getDbDumper($connectionName)->dumpToFile($dumpPath);
72
73
        $file = fopen($dumpPath, 'r');
74
75
        $disk->put($fileName, $file);
76
77
        fclose($file);
78
79
        $directory->delete();
80
    }
81
}
82