Completed
Pull Request — master (#636)
by
unknown
03:58
created

BackupJob::onlyDbName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 14
rs 9.4285
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
    public function onlyDbName(array $dbNames): self
54
    {
55
        // Remove any DbDumper whose key does not equal any dbNames value
56
		$allowedNames = collect($dbNames);
57
58
        $filteredDumpers = $this->dbDumpers->filter(
59
			function ($value, $key) use($allowedNames){
60
				return $allowedNames->contains($key);
61
            });
62
63
        $this->dbDumpers = $filteredDumpers;
64
65
        return $this;
66
    }
67
    public function dontBackupDatabases(): self
68
    {
69
        $this->dbDumpers = new Collection();
70
71
        return $this;
72
    }
73
74
    public function disableNotifications(): self
75
    {
76
        $this->sendNotifications = false;
77
78
        return $this;
79
    }
80
81
    public function setDefaultFilename(): self
82
    {
83
        $this->filename = Carbon::now()->format('Y-m-d-H-i-s').'.zip';
84
85
        return $this;
86
    }
87
88
    public function setFileSelection(FileSelection $fileSelection): self
89
    {
90
        $this->fileSelection = $fileSelection;
91
92
        return $this;
93
    }
94
95
    public function setDbDumpers(Collection $dbDumpers): self
96
    {
97
        $this->dbDumpers = $dbDumpers;
98
99
        return $this;
100
    }
101
102
    public function setFilename(string $filename): self
103
    {
104
        $this->filename = $filename;
105
106
        return $this;
107
    }
108
109
    public function onlyBackupTo(string $diskName): self
110
    {
111
        $this->backupDestinations = $this->backupDestinations->filter(function (BackupDestination $backupDestination) use ($diskName) {
112
            return $backupDestination->diskName() === $diskName;
113
        });
114
115
        if (! count($this->backupDestinations)) {
116
            throw InvalidBackupJob::destinationDoesNotExist($diskName);
117
        }
118
119
        return $this;
120
    }
121
122
    public function setBackupDestinations(Collection $backupDestinations): self
123
    {
124
        $this->backupDestinations = $backupDestinations;
125
126
        return $this;
127
    }
128
129
    public function run()
130
    {
131
        $this->temporaryDirectory = (new TemporaryDirectory(storage_path('app/backup-temp')))
132
            ->name('temp')
133
            ->force()
134
            ->create()
135
            ->empty();
136
137
        try {
138
            if (! count($this->backupDestinations)) {
139
                throw InvalidBackupJob::noDestinationsSpecified();
140
            }
141
142
            $manifest = $this->createBackupManifest();
143
144
            if (! $manifest->count()) {
145
                throw InvalidBackupJob::noFilesToBeBackedUp();
146
            }
147
148
            $zipFile = $this->createZipContainingEveryFileInManifest($manifest);
149
150
            $this->copyToBackupDestinations($zipFile);
151
        }
152
        catch (Exception $exception) {
153
            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...
154
155
            $this->sendNotification(new BackupHasFailed($exception));
156
157
            $this->temporaryDirectory->delete();
158
159
            throw $exception;
160
        }
161
162
        $this->temporaryDirectory->delete();
163
    }
164
165
    protected function createBackupManifest(): Manifest
166
    {
167
        $databaseDumps = $this->dumpDatabases();
168
169
        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...
170
171
        $manifest = Manifest::create($this->temporaryDirectory->path('manifest.txt'))
172
            ->addFiles($databaseDumps)
173
            ->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...
174
175
        $this->sendNotification(new BackupManifestWasCreated($manifest));
176
177
        return $manifest;
178
    }
179
180
    public function filesToBeBackedUp()
181
    {
182
        $this->fileSelection->excludeFilesFrom($this->directoriesUsedByBackupJob());
183
184
        return $this->fileSelection->selectedFiles();
185
    }
186
187
    protected function directoriesUsedByBackupJob(): array
188
    {
189
        return $this->backupDestinations
190
            ->filter(function (BackupDestination $backupDestination) {
191
                return $backupDestination->filesystemType() === 'local';
192
            })
193
            ->map(function (BackupDestination $backupDestination) {
194
                return $backupDestination->disk()->getDriver()->getAdapter()->applyPathPrefix('').$backupDestination->backupName();
195
            })
196
            ->each(function (string $backupDestinationDirectory) {
197
                $this->fileSelection->excludeFilesFrom($backupDestinationDirectory);
198
            })
199
            ->push($this->temporaryDirectory->path())
200
            ->toArray();
201
    }
202
203
    protected function createZipContainingEveryFileInManifest(Manifest $manifest)
204
    {
205
        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...
206
207
        $pathToZip = $this->temporaryDirectory->path(config('backup.backup.destination.filename_prefix').$this->filename);
208
209
        $zip = Zip::createForManifest($manifest, $pathToZip);
210
211
        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...
212
213
        $this->sendNotification(new BackupZipWasCreated($pathToZip));
214
215
        return $pathToZip;
216
    }
217
218
    /**
219
     * Dumps the databases to the given directory.
220
     * Returns an array with paths to the dump files.
221
     *
222
     * @return array
223
     */
224
    protected function dumpDatabases(): array
225
    {
226
        return $this->dbDumpers->map(function (DbDumper $dbDumper) {
227
            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...
228
229
            $dbType = mb_strtolower(basename(str_replace('\\', '/', get_class($dbDumper))));
230
231
            $dbName = $dbDumper instanceof Sqlite ? 'database' : $dbDumper->getDbName();
232
233
            $fileName = "{$dbType}-{$dbName}.sql";
234
235
            $temporaryFilePath = $this->temporaryDirectory->path('db-dumps'.DIRECTORY_SEPARATOR.$fileName);
236
237
            $dbDumper->dumpToFile($temporaryFilePath);
238
239
            if (config('backup.backup.gzip_database_dump')) {
240
                consoleOutput()->info("Gzipping {$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...
241
242
                $compressedDumpPath = Gzip::compress($temporaryFilePath);
243
244
                return $compressedDumpPath;
245
            }
246
247
            return $temporaryFilePath;
248
        })->toArray();
249
    }
250
251
    protected function copyToBackupDestinations(string $path)
252
    {
253
        $this->backupDestinations->each(function (BackupDestination $backupDestination) use ($path) {
254
            try {
255
                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...
256
257
                $backupDestination->write($path);
258
259
                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...
260
261
                $this->sendNotification(new BackupWasSuccessful($backupDestination));
262
            }
263
            catch (Exception $exception) {
264
                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...
265
266
                $this->sendNotification(new BackupHasFailed($exception, $backupDestination ?? null));
267
            }
268
        });
269
    }
270
271
    protected function sendNotification($notification)
272
    {
273
        if ($this->sendNotifications) {
274
            event($notification);
275
        }
276
    }
277
}
278