71 lines
2.3 KiB
PHP
71 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use RuntimeException;
|
|
use Throwable;
|
|
|
|
class UploadDatabaseBackup extends Command
|
|
{
|
|
protected $signature = 'backup:upload {source : Absolute path to the backup file} {destination : Object path on the configured disk}';
|
|
|
|
protected $description = 'Upload a database backup file to private object storage';
|
|
|
|
public function handle(): int
|
|
{
|
|
$source = (string) $this->argument('source');
|
|
$destination = ltrim((string) $this->argument('destination'), '/');
|
|
$diskName = (string) config('backup.database.disk', 's3');
|
|
|
|
if (! is_file($source) || ! is_readable($source)) {
|
|
$this->error("Backup file is not readable: {$source}");
|
|
|
|
return self::FAILURE;
|
|
}
|
|
|
|
if ($destination === '' || str_contains($destination, '..')) {
|
|
$this->error('The destination object path is invalid.');
|
|
|
|
return self::FAILURE;
|
|
}
|
|
|
|
$stream = fopen($source, 'rb');
|
|
if ($stream === false) {
|
|
$this->error("Could not open backup file: {$source}");
|
|
|
|
return self::FAILURE;
|
|
}
|
|
|
|
try {
|
|
$disk = Storage::disk($diskName);
|
|
$uploaded = $disk->writeStream($destination, $stream, [
|
|
'visibility' => 'private',
|
|
'ContentType' => 'application/gzip',
|
|
]);
|
|
|
|
if (! $uploaded || ! $disk->exists($destination)) {
|
|
throw new RuntimeException('The storage driver did not confirm the uploaded object.');
|
|
}
|
|
|
|
$localSize = filesize($source);
|
|
$remoteSize = $disk->size($destination);
|
|
if ($localSize === false || $remoteSize !== $localSize) {
|
|
throw new RuntimeException("Uploaded object size mismatch: local={$localSize}, remote={$remoteSize}");
|
|
}
|
|
|
|
$this->info("Uploaded {$destination} ({$remoteSize} bytes) to {$diskName}.");
|
|
|
|
return self::SUCCESS;
|
|
} catch (Throwable $exception) {
|
|
report($exception);
|
|
$this->error("Backup upload failed: {$exception->getMessage()}");
|
|
|
|
return self::FAILURE;
|
|
} finally {
|
|
fclose($stream);
|
|
}
|
|
}
|
|
}
|