Completed
Push — master ( 4c4bf1...e6f595 )
by Freek
01:55
created

BackupJob::dumpDatabases()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 13
nc 1
nop 0
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Backup\Tasks\Backup;
4
5
use Exception;
6
use Carbon\Carbon;
7
use Spatie\DbDumper\DbDumper;
8
use Illuminate\Support\Collection;
9
use Spatie\DbDumper\Databases\Sqlite;
10
use Spatie\Backup\Events\BackupHasFailed;
11
use Spatie\Backup\Events\BackupWasSuccessful;
12
use Spatie\Backup\Events\BackupZipWasCreated;
13
use Spatie\Backup\Exceptions\InvalidBackupJob;
14
use Spatie\TemporaryDirectory\TemporaryDirectory;
15
use Spatie\Backup\Events\BackupManifestWasCreated;
16
use Spatie\Backup\BackupDestination\BackupDestination;
17
18
class BackupJob
19
{
20
    /** @var \Spatie\Backup\Tasks\Backup\FileSelection */
21
    protected $fileSelection;
22
23
    /** @var \Illuminate\Support\Collection */
24
    protected $dbDumpers;
25
26
    /** @var \Illuminate\Support\Collection */
27
    protected $backupDestinations;
28
29
    /** @var string */
30
    protected $filename;
31
32
    /** @var \Spatie\TemporaryDirectory\TemporaryDirectory */
33
    protected $temporaryDirectory;
34
35
    /** @var bool */
36
    protected $sendNotifications = true;
37
38
    public function __construct()
39
    {
40
        $this->dontBackupFilesystem();
41
        $this->dontBackupDatabases();
42
        $this->setDefaultFilename();
43
44
        $this->backupDestinations = new Collection();
45
    }
46
47
    public function dontBackupFilesystem(): self
48
    {
49
        $this->fileSelection = FileSelection::create();
50
51
        return $this;
52
    }
53
54
    public function onlyDbName(array $allowedDbNames): self
55
    {
56
        $this->dbDumpers = $this->dbDumpers->filter(
57
            function (DbDumper $dbDumper, string $connectionName) use ($allowedDbNames) {
58
                return in_array($connectionName, $allowedDbNames);
59
            });
60
61
        return $this;
62
    }
63
64
    public function dontBackupDatabases(): self
65
    {
66
        $this->dbDumpers = new Collection();
67
68
        return $this;
69
    }
70
71
    public function disableNotifications(): self
72
    {
73
        $this->sendNotifications = false;
74
75
        return $this;
76
    }
77
78
    public function setDefaultFilename(): self
79
    {
80
        $this->filename = Carbon::now()->format('Y-m-d-H-i-s').'.zip';
81
82
        return $this;
83
    }
84
85
    public function setFileSelection(FileSelection $fileSelection): self
86
    {
87
        $this->fileSelection = $fileSelection;
88
89
        return $this;
90
    }
91
92
    public function setDbDumpers(Collection $dbDumpers): self
93
    {
94
        $this->dbDumpers = $dbDumpers;
95
96
        return $this;
97
    }
98
99
    public function setFilename(string $filename): self
100
    {
101
        $this->filename = $filename;
102
103
        return $this;
104
    }
105
106
    public function onlyBackupTo(string $diskName): self
107
    {
108
        $this->backupDestinations = $this->backupDestinations->filter(function (BackupDestination $backupDestination) use ($diskName) {
109
            return $backupDestination->diskName() === $diskName;
110
        });
111
112
        if (! count($this->backupDestinations)) {
113
            throw InvalidBackupJob::destinationDoesNotExist($diskName);
114
        }
115
116
        return $this;
117
    }
118
119
    public function setBackupDestinations(Collection $backupDestinations): self
120
    {
121
        $this->backupDestinations = $backupDestinations;
122
123
        return $this;
124
    }
125
126
    public function run()
127
    {
128
        $this->temporaryDirectory = (new TemporaryDirectory(storage_path('app/backup-temp')))
129
            ->name('temp')
130
            ->force()
131
            ->create()
132
            ->empty();
133
134
        try {
135
            if (! count($this->backupDestinations)) {
136
                throw InvalidBackupJob::noDestinationsSpecified();
137
            }
138
139
            $manifest = $this->createBackupManifest();
140
141
            if (! $manifest->count()) {
142
                throw InvalidBackupJob::noFilesToBeBackedUp();
143
            }
144
145
            $zipFile = $this->createZipContainingEveryFileInManifest($manifest);
146
147
            $this->copyToBackupDestinations($zipFile);
148
        } catch (Exception $exception) {
149
            consoleOutput()->error("Backup failed because {$exception->getMessage()}.".PHP_EOL.$exception->getTraceAsString());
0 ignored issues
show
Documentation Bug introduced by
The method error does not exist on object<Spatie\Backup\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
150
151
            $this->sendNotification(new BackupHasFailed($exception));
152
153
            $this->temporaryDirectory->delete();
154
155
            throw $exception;
156
        }
157
158
        $this->temporaryDirectory->delete();
159
    }
160
161
    protected function createBackupManifest(): Manifest
162
    {
163
        $databaseDumps = $this->dumpDatabases();
164
165
        consoleOutput()->info('Determining files to backup...');
0 ignored issues
show
Documentation Bug introduced by
The method info does not exist on object<Spatie\Backup\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
166
167
        $manifest = Manifest::create($this->temporaryDirectory->path('manifest.txt'))
168
            ->addFiles($databaseDumps)
169
            ->addFiles($this->filesToBeBackedUp());
0 ignored issues
show
Documentation introduced by
$this->filesToBeBackedUp() is of type object<Generator>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
170
171
        $this->sendNotification(new BackupManifestWasCreated($manifest));
172
173
        return $manifest;
174
    }
175
176
    public function filesToBeBackedUp()
177
    {
178
        $this->fileSelection->excludeFilesFrom($this->directoriesUsedByBackupJob());
179
180
        return $this->fileSelection->selectedFiles();
181
    }
182
183
    protected function directoriesUsedByBackupJob(): array
184
    {
185
        return $this->backupDestinations
186
            ->filter(function (BackupDestination $backupDestination) {
187
                return $backupDestination->filesystemType() === 'local';
188
            })
189
            ->map(function (BackupDestination $backupDestination) {
190
                return $backupDestination->disk()->getDriver()->getAdapter()->applyPathPrefix('').$backupDestination->backupName();
191
            })
192
            ->each(function (string $backupDestinationDirectory) {
193
                $this->fileSelection->excludeFilesFrom($backupDestinationDirectory);
194
            })
195
            ->push($this->temporaryDirectory->path())
196
            ->toArray();
197
    }
198
199
    protected function createZipContainingEveryFileInManifest(Manifest $manifest)
200
    {
201
        consoleOutput()->info("Zipping {$manifest->count()} files...");
0 ignored issues
show
Documentation Bug introduced by
The method info does not exist on object<Spatie\Backup\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
202
203
        $pathToZip = $this->temporaryDirectory->path(config('backup.backup.destination.filename_prefix').$this->filename);
204
205
        $zip = Zip::createForManifest($manifest, $pathToZip);
206
207
        consoleOutput()->info("Created zip containing {$zip->count()} files. Size is {$zip->humanReadableSize()}");
0 ignored issues
show
Documentation Bug introduced by
The method info does not exist on object<Spatie\Backup\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
208
209
        $this->sendNotification(new BackupZipWasCreated($pathToZip));
210
211
        return $pathToZip;
212
    }
213
214
    /**
215
     * Dumps the databases to the given directory.
216
     * Returns an array with paths to the dump files.
217
     *
218
     * @return array
219
     */
220
    protected function dumpDatabases(): array
221
    {
222
        return $this->dbDumpers->map(function (DbDumper $dbDumper) {
223
            consoleOutput()->info("Dumping database {$dbDumper->getDbName()}...");
0 ignored issues
show
Documentation Bug introduced by
The method info does not exist on object<Spatie\Backup\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
224
225
            $dbType = mb_strtolower(basename(str_replace('\\', '/', get_class($dbDumper))));
226
227
            $dbName = $dbDumper instanceof Sqlite ? 'database' : $dbDumper->getDbName();
228
229
            $fileName = "{$dbType}-{$dbName}.sql";
230
231
            if (config('backup.backup.gzip_database_dump')) {
232
                $fileName .= '.gz';
233
                $dbDumper->enableCompression();
234
            }
235
236
            $temporaryFilePath = $this->temporaryDirectory->path('db-dumps'.DIRECTORY_SEPARATOR.$fileName);
237
238
            $dbDumper->dumpToFile($temporaryFilePath);
239
240
            return $temporaryFilePath;
241
        })->toArray();
242
    }
243
244
    protected function copyToBackupDestinations(string $path)
245
    {
246
        $this->backupDestinations->each(function (BackupDestination $backupDestination) use ($path) {
247
            try {
248
                consoleOutput()->info("Copying zip to disk named {$backupDestination->diskName()}...");
0 ignored issues
show
Documentation Bug introduced by
The method info does not exist on object<Spatie\Backup\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
249
250
                $backupDestination->write($path);
251
252
                consoleOutput()->info("Successfully copied zip to disk named {$backupDestination->diskName()}.");
0 ignored issues
show
Documentation Bug introduced by
The method info does not exist on object<Spatie\Backup\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
253
254
                $this->sendNotification(new BackupWasSuccessful($backupDestination));
255
            } catch (Exception $exception) {
256
                consoleOutput()->error("Copying zip failed because: {$exception->getMessage()}.");
0 ignored issues
show
Documentation Bug introduced by
The method error does not exist on object<Spatie\Backup\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
257
258
                $this->sendNotification(new BackupHasFailed($exception, $backupDestination ?? null));
259
            }
260
        });
261
    }
262
263
    protected function sendNotification($notification)
264
    {
265
        if ($this->sendNotifications) {
266
            event($notification);
267
        }
268
    }
269
}
270