|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace AsLong\Backup; |
| 4 | + |
| 5 | +use Carbon\Carbon; |
| 6 | +use Illuminate\Console\Command; |
| 7 | +use Symfony\Component\Process\Exception\ProcessFailedException; |
| 8 | +use Symfony\Component\Process\Process; |
| 9 | + |
| 10 | +class BackupDatabase extends Command |
| 11 | +{ |
| 12 | + /** |
| 13 | + * The name and signature of the console command. |
| 14 | + * |
| 15 | + * @var string |
| 16 | + */ |
| 17 | + protected $signature = 'db:backup'; |
| 18 | + |
| 19 | + /** |
| 20 | + * The console command description. |
| 21 | + * |
| 22 | + * @var string |
| 23 | + */ |
| 24 | + protected $description = 'Backup the database'; |
| 25 | + |
| 26 | + /** |
| 27 | + * Create a new command instance. |
| 28 | + * |
| 29 | + * @return void |
| 30 | + */ |
| 31 | + public function __construct() |
| 32 | + { |
| 33 | + parent::__construct(); |
| 34 | + |
| 35 | + $this->process = new Process(sprintf( |
| 36 | + 'mysqldump -u%s -p%s %s > %s', |
| 37 | + config('database.connections.mysql.username'), |
| 38 | + config('database.connections.mysql.password'), |
| 39 | + config('database.connections.mysql.database'), |
| 40 | + storage_path('backups/backup_' . date('Y-m-d') . '.sql') |
| 41 | + )); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Execute the console command. |
| 46 | + * |
| 47 | + * @return mixed |
| 48 | + */ |
| 49 | + public function handle() |
| 50 | + { |
| 51 | + try { |
| 52 | + // 删除N天之前的备份 |
| 53 | + $directory = storage_path('backups/'); |
| 54 | + $files = scandir($directory); |
| 55 | + |
| 56 | + foreach ($files as $file) { |
| 57 | + if (!in_array($file, ['.', '..']) && Carbon::now()->diffIndays(substr($file, 7, 10)) >= env('DB_BACKUP_DAYS', 5)) { |
| 58 | + unlink($directory . $file); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + $this->process->mustRun(); |
| 63 | + |
| 64 | + $this->info('The backup has been proceed successfully.'); |
| 65 | + } catch (ProcessFailedException $exception) { |
| 66 | + $this->error('The backup process has been failed.'); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments