Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
14 / 14 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| BackupDbCommand | |
100.00% |
14 / 14 |
|
100.00% |
2 / 2 |
3 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| __invoke | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace App\Command; |
| 6 | |
| 7 | use App\Service\BackupManager; |
| 8 | use App\Service\EmailHelper; |
| 9 | use Symfony\Component\Clock\ClockInterface; |
| 10 | use Symfony\Component\Console\Attribute\AsCommand; |
| 11 | use Symfony\Component\Console\Command\Command; |
| 12 | use Symfony\Component\Console\Output\OutputInterface; |
| 13 | use Symfony\Component\Mailer\MailerInterface; |
| 14 | |
| 15 | #[AsCommand(name: 'app:backup:db', description: 'Backup the database')] |
| 16 | class BackupDbCommand |
| 17 | { |
| 18 | public function __construct( |
| 19 | private readonly BackupManager $backupManager, |
| 20 | private readonly EmailHelper $emailHelper, |
| 21 | private readonly MailerInterface $mailer, |
| 22 | private readonly ClockInterface $clock, |
| 23 | ) {} |
| 24 | |
| 25 | public function __invoke(OutputInterface $output): int |
| 26 | { |
| 27 | $date = $this->clock->now()->format('Y-m-d_H-i-s'); |
| 28 | $backupFile = sys_get_temp_dir().sprintf('/backup_%s.sql', $date); |
| 29 | |
| 30 | $command = $this->backupManager->getBackupCommand().' > '.escapeshellarg($backupFile); |
| 31 | |
| 32 | system($command, $result); |
| 33 | |
| 34 | if ($result !== 0) { |
| 35 | $output->writeln('<error>Database backup failed</error>'); |
| 36 | return Command::FAILURE; |
| 37 | } |
| 38 | |
| 39 | $email = $this->emailHelper |
| 40 | ->createAdminEmail('Backup: '.$date) |
| 41 | ->text('Backup: '.$date) |
| 42 | ->attachFromPath($backupFile); |
| 43 | |
| 44 | $this->mailer->send($email); |
| 45 | |
| 46 | return Command::SUCCESS; |
| 47 | } |
| 48 | } |