Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.00% covered (success)
96.00%
24 / 25
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
MonitorBackupCommand
96.00% covered (success)
96.00%
24 / 25
66.67% covered (warning)
66.67%
2 / 3
13
0.00% covered (danger)
0.00%
0 / 1
 getAllowedAppEnvs
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 getLatestBackupTimestamp
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
7.04
1<?php
2
3namespace Olz\Command;
4
5use Olz\Command\Common\OlzCommand;
6use Symfony\Component\Console\Attribute\AsCommand;
7use Symfony\Component\Console\Command\Command;
8use Symfony\Component\Console\Input\InputInterface;
9use Symfony\Component\Console\Output\OutputInterface;
10
11#[AsCommand(name: 'olz:monitor-backup')]
12class MonitorBackupCommand extends OlzCommand {
13    public const MAX_AGE_SECONDS = 86400 * 2;
14
15    public const BACKUP_FILENAME_REGEX = '/^backup-([0-9]{4}-[0-9]{2}-[0-9]{2})\.crypt\.json$/';
16
17    /** @return array<string> */
18    protected function getAllowedAppEnvs(): array {
19        return ['dev', 'test', 'staging', 'prod'];
20    }
21
22    protected function handle(InputInterface $input, OutputInterface $output): int {
23        $backups_path = "{$this->envUtils()->getPrivatePath()}backups/";
24        if (!is_dir($backups_path)) {
25            throw new \Exception("Expected backups directory at {$backups_path}");
26        }
27        $latest_timestamp = $this->getLatestBackupTimestamp($backups_path);
28        if ($latest_timestamp === null) {
29            throw new \Exception("No database backup found in {$backups_path}");
30        }
31        $now_timestamp = strtotime($this->dateUtils()->getIsoNow()) ?: 0;
32        $age_seconds = $now_timestamp - $latest_timestamp;
33        if ($age_seconds > self::MAX_AGE_SECONDS) {
34            $latest = date('Y-m-d', $latest_timestamp);
35            throw new \Exception("Latest database backup ({$latest}) is older than 2 days");
36        }
37        $this->logAndOutput("OK:");
38        return Command::SUCCESS;
39    }
40
41    protected function getLatestBackupTimestamp(string $backups_path): ?int {
42        $latest_timestamp = null;
43        $filenames = scandir($backups_path) ?: [];
44        foreach ($filenames as $filename) {
45            if (!preg_match(self::BACKUP_FILENAME_REGEX, $filename, $matches)) {
46                continue;
47            }
48            $timestamp = strtotime($matches[1]);
49            if ($timestamp === false) {
50                continue;
51            }
52            if ($latest_timestamp === null || $timestamp > $latest_timestamp) {
53                $latest_timestamp = $timestamp;
54            }
55        }
56        return $latest_timestamp;
57    }
58}