Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Console\Commands;
- use Illuminate\Console\Command;
- use Symfony\Component\Process\Process;
- use Symfony\Component\Process\Exception\ProcessFailedException;
- use Carbon\Carbon;
- class MysqlDump extends Command
- {
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'db:dump';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = 'Dump the mysql database api in file storage';
- /**
- * The directory name for dump storage - params from config
- * @var string
- */
- protected $directory;
- /**
- * Max file instorage for rotation - params from config
- * @var int
- */
- protected $max;
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct()
- {
- parent::__construct();
- $this->directory = config('dump.storage');
- $this->max = config('dump.max') ?? 5;
- }
- /**
- * Execute the console command.
- *
- * @return mixed
- */
- public function handle()
- {
- $command = $this->generateCommand();
- $this->process = new Process($command);
- $this->process->run();
- if (!$this->process->isSuccessful()) {
- throw new ProcessFailedException($this->process);
- }
- $this->rotate();
- $this->info('The database dumped!');
- }
- public function rotate () {
- $f = new \FilesystemIterator($this->directory, \FilesystemIterator::SKIP_DOTS);
- if (iterator_count($f) > $this->max) {
- $stack = [];
- foreach ($f as $key => $value) {
- $stack[] = $key;
- }
- rsort($stack);
- $filesToDelete = array_slice($stack, $this->max, null, true);
- if (!empty($filesToDelete)) {
- foreach ($filesToDelete as $file) {
- unlink($file);
- }
- }
- }
- }
- public function generateCommand() {
- $db = env('DB_DATABASE');
- $pass = env('DB_PASSWORD');
- $user = env('DB_USERNAME');
- $host = env('DB_HOST');
- if (!is_dir($this->directory)) {
- $this->info('The dump storage directory is not set, please add a dumps directory in database root directory!');
- exit;
- }
- $prefix = Carbon::now()->format('d-m-Y_H:i:s');
- $filename = sprintf('%s/%s_%s', $this->directory, $prefix, config('dump.filename'));
- $archive = basename($filename);
- return <<<EOF
- mysqldump -h$host -u$user -p$pass $db > $filename;
- tar cfz database/dumps/$archive.tar.gz database/dumps/$archive;
- rm $filename;
- EOF;
- }
- }
Add Comment
Please, Sign In to add comment