Skip to content

Commit

Permalink
Add full backup command
Browse files Browse the repository at this point in the history
  • Loading branch information
karlomikus committed Oct 2, 2023
1 parent 7e12a73 commit f6908df
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
38 changes: 38 additions & 0 deletions app/Console/Commands/BarFullBackup.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Kami\Cocktail\Console\Commands;

use Illuminate\Console\Command;
use Kami\Cocktail\Export\FullBackupToZip;

class BarFullBackup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'bar:full-backup';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a .zip file with the full backup of your files';

public function __construct(private FullBackupToZip $exporter)
{
parent::__construct();
}

/**
* Execute the console command.
*/
public function handle(): int
{
$this->exporter->process();

return Command::SUCCESS;
}
}
56 changes: 56 additions & 0 deletions app/Export/FullBackupToZip.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

namespace Kami\Cocktail\Export;

use ZipArchive;
use Carbon\Carbon;
use Illuminate\Log\LogManager;
use Illuminate\Support\Facades\File;
use Kami\Cocktail\Exceptions\ExportException;

class FullBackupToZip
{
public function __construct(
private readonly LogManager $log,
) {
}

public function process(?string $exportPath = null): string
{
$version = config('bar-assistant.version');
$meta = [
'version' => $version,
'date' => Carbon::now()->toJSON(),
'called_from' => __CLASS__,
];

$zip = new ZipArchive();

File::ensureDirectoryExists(storage_path('bar-assistant/backups'));

$filename = storage_path(sprintf('bar-assistant/backups/%s_%s.zip', Carbon::now()->format('Ymdhi'), 'bass-backup'));
if ($exportPath) {
$filename = $exportPath;
}

if ($zip->open($filename, ZipArchive::CREATE) !== true) {
$message = sprintf('Error creating zip archive with filepath "%s"', $filename);
$this->log->error($message);

throw new ExportException($message);
}

$zip->addGlob(storage_path('bar-assistant/*.sqlite'), options: ['remove_path' => storage_path('bar-assistant')]);
$zip->addGlob(storage_path('bar-assistant/uploads/*/*/*'), options: ['remove_path' => storage_path('bar-assistant')]);

if ($metaContent = json_encode($meta)) {
$zip->addFromString('_meta.json', $metaContent);
}

$zip->close();

return $filename;
}
}

0 comments on commit f6908df

Please sign in to comment.