Completed
Pull Request — master (#189)
by Barry vd.
02:55
created

BackupJob::setFileSelection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Backup\Tasks\Backup;
4
5
use Illuminate\Support\Collection;
6
use Spatie\Backup\BackupDestination\Backup;
7
use Spatie\Backup\BackupDestination\BackupDestination;
8
use Spatie\Backup\Events\BackupHasFailed;
9
use Spatie\Backup\Events\BackupWasSuccessful;
10
use Spatie\Backup\Events\BackupZipWasCreated;
11
use Spatie\Backup\Exceptions\InvalidBackupJob;
12
use Spatie\Backup\Helpers\Format;
13
use Spatie\DbDumper\DbDumper;
14
use Exception;
15
16
class BackupJob
17
{
18
    /**  @var \Spatie\Backup\Tasks\Backup\FileSelection */
19
    protected $fileSelection;
20
21
    /** @var \Illuminate\Support\Collection */
22
    protected $dbDumpers;
23
24
    /** @var \Illuminate\Support\Collection */
25
    protected $backupDestinations;
26
27
    /** @var \Spatie\Backup\Tasks\Backup\TemporaryDirectory */
28
    protected $temporaryDirectory;
29
30
    /** @var string  */
31
    protected $filename;
32
33
    public function __construct()
34
    {
35
        $this->doNotBackupFilesystem();
36
        $this->doNotBackupDatabases();
37
        $this->setDefaultFilename();
38
39
        $this->backupDestinations = new Collection();
40
    }
41
42
    /**
43
     * @return \Spatie\Backup\Tasks\Backup\BackupJob
44
     */
45
    public function doNotBackupFilesystem()
46
    {
47
        $this->fileSelection = FileSelectionFactory::noFiles();
48
49
        return $this;
50
    }
51
52
    /**
53
     * @return \Spatie\Backup\Tasks\Backup\BackupJob
54
     */
55
    public function doNotBackupDatabases()
56
    {
57
        $this->dbDumpers = new Collection();
58
59
        return $this;
60
    }
61
62
    /**
63
     * @return \Spatie\Backup\Tasks\Backup\BackupJob
64
     */
65
    public function setDefaultFilename()
66
    {
67
        $this->filename = date('Y-m-d-His').'.zip';
68
69
        return $this;
70
    }
71
72
    /**
73
     * @param \Spatie\Backup\Tasks\Backup\FileSelection $fileSelection
74
     *
75
     * @return \Spatie\Backup\Tasks\Backup\BackupJob
76
     */
77
    public function setFileSelection(FileSelection $fileSelection)
78
    {
79
        $this->fileSelection = $fileSelection;
80
81
        return $this;
82
    }
83
84
    /**
85
     * @param array $dbDumpers
86
     *
87
     * @return \Spatie\Backup\Tasks\Backup\BackupJob
88
     */
89
    public function setDbDumpers(array $dbDumpers)
90
    {
91
        $this->dbDumpers = Collection::make($dbDumpers);
92
93
        return $this;
94
    }
95
96
    /**
97
     * @param string $filename
98
     *
99
     * @return \Spatie\Backup\Tasks\Backup\BackupJob
100
     */
101
    public function setFilename($filename)
102
    {
103
        $this->filename = $filename;
104
105
        return $this;
106
    }
107
108
    /**
109
     * @param string $diskName
110
     *
111
     * @return \Spatie\Backup\Tasks\Backup\BackupJob
112
     *
113
     * @throws \Spatie\Backup\Exceptions\InvalidBackupJob
114
     */
115
    public function backupOnlyTo($diskName)
116
    {
117
        $this->backupDestinations = $this->backupDestinations->filter(function (BackupDestination $backupDestination) use ($diskName) {
118
            return $backupDestination->getDiskName() === $diskName;
119
        });
120
121
        if (!count($this->backupDestinations)) {
122
            throw InvalidBackupJob::destinationDoesNotExist($diskName);
123
        }
124
125
        return $this;
126
    }
127
128
    /**
129
     * @param \Illuminate\Support\Collection $backupDestinations
130
     *
131
     * @return \Spatie\Backup\Tasks\Backup\BackupJob
132
     */
133
    public function setBackupDestinations(Collection $backupDestinations)
134
    {
135
        $this->backupDestinations = $backupDestinations;
136
137
        return $this;
138
    }
139
140
    public function run()
141
    {
142
        try {
143
            if (!count($this->backupDestinations)) {
144
                throw InvalidBackupJob::noDestinationsSpecified();
145
            }
146
147
            $this->temporaryDirectory = TemporaryDirectory::create();
148
149
            $zip = $this->createZipContainingAllFilesToBeBackedUp();
150
151
            $this->copyToBackupDestinations($zip);
152
153
            $this->temporaryDirectory->delete();
154
        } catch (Exception $exception) {
155
            consoleOutput()->error("Backup 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...
156
157
            event(new BackupHasFailed($exception));
158
        }
159
    }
160
161
    /**
162
     * @return \Spatie\Backup\Tasks\Backup\Zip
163
     */
164
    protected function createZipContainingAllFilesToBeBackedUp()
165
    {
166
        $zip = Zip::create($this->temporaryDirectory->getPath($this->filename));
167
168
        $this->addDatabaseDumpsToZip($zip);
169
170
        $this->addSelectedFilesToZip($zip);
171
172
        event(new BackupZipWasCreated($zip));
173
174
        return $zip;
175
    }
176
177
    /**
178
     * @param \Spatie\Backup\Tasks\Backup\Zip $zip
179
     */
180
    protected function addSelectedFilesToZip(Zip $zip)
181
    {
182
        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...
183
184
        $zip->add($this->fileSelection->getSelectedFiles());
0 ignored issues
show
Documentation introduced by
$this->fileSelection->getSelectedFiles() is of type object<Generator>, but the function expects a string|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...
185
186
        consoleOutput()->info("Zipped {$zip->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...
187
    }
188
189
    /**
190
     * @param \Spatie\Backup\Tasks\Backup\Zip $zip
191
     */
192
    protected function addDatabaseDumpsToZip(Zip $zip)
193
    {
194
        $this->dbDumpers->each(function (DbDumper $dbDumper) use ($zip) {
195
196
            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...
197
198
            $fileName = $dbDumper->getDbName().'.sql';
199
            $temporaryFile = $this->temporaryDirectory->getPath($fileName);
200
            $dbDumper->dumpToFile($temporaryFile);
201
202
            $zip->add($temporaryFile, $fileName);
203
        });
204
    }
205
206
    /**
207
     * @param \Spatie\Backup\Tasks\Backup\Zip $zip
208
     */
209
    protected function copyToBackupDestinations(Zip $zip)
210
    {
211
        $this->backupDestinations->each(function (BackupDestination $backupDestination) use ($zip) {
212
213
            try {
214
                $fileSize = Format::getHumanReadableSize($zip->getSize());
215
216
                $fileName = pathinfo($zip->getPath(), PATHINFO_BASENAME);
217
218
                consoleOutput()->info("Copying {$fileName} (size: {$fileSize}) to disk named {$backupDestination->getDiskName()}...");
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...
219
220
                $backupDestination->write($zip->getPath());
221
222
                consoleOutput()->info("Successfully copied .zip file to disk named {$backupDestination->getDiskName()}.");
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...
223
224
                event(new BackupWasSuccessful($backupDestination));
225
            } catch (Exception $exception) {
226
                consoleOutput()->error("Copying .zip file 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...
227
228
                event(new BackupHasFailed($exception));
229
            }
230
        });
231
    }
232
}
233