Passed
Push — dev ( 7914d2...bbc331 )
by Janko
10:29
created

DatabaseBackup::backup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 0
dl 0
loc 13
ccs 0
cts 11
cp 0
crap 2
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace Stu\Module\Maintenance;
4
5
use Noodlehaus\ConfigInterface;
6
use Override;
0 ignored issues
show
Bug introduced by
The type Override was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use RuntimeException;
8
9
final class DatabaseBackup implements MaintenanceHandlerInterface
10
{
11 1
    public function __construct(private ConfigInterface $config) {}
12
13
    #[Override]
14
    public function handle(): void
15
    {
16
        $this->cleanup();
17
        $this->backup();
18
    }
19
20
    private function cleanup(): void
21
    {
22
        $backup_dir = $this->config->get('db.backup_dir');
23
24
        $dir = dir($backup_dir);
25
        if ($dir === false) {
26
            throw new RuntimeException('error opening backup directory');
27
        }
28
        while ($file = $dir->read()) {
29
            $filename = sprintf('%s/%s', $backup_dir, $file);
30
31
            if (is_file($filename) && filectime($filename) < time() - (int)$this->config->get('db.backup_cycle_time')) {
32
                unlink($filename);
33
            }
34
        }
35
        $dir->close();
36
    }
37
38
    private function backup(): void
39
    {
40
        $cmd = sprintf(
41
            'PGPASSWORD="%s" pg_dump -Fc -U %s -h %s %s > %s/%s.dump',
42
            $this->config->get('db.pass'),
43
            $this->config->get('db.user'),
44
            $this->config->get('db.host'),
45
            $this->config->get('db.database'),
46
            $this->config->get('db.backup_dir'),
47
            date("d-m-Y", time())
48
        );
49
50
        system($cmd);
51
    }
52
}
53