Guest User

Untitled

a guest
Feb 3rd, 2018
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Console\Commands;
  4.  
  5. use Illuminate\Console\Command;
  6. use Symfony\Component\Process\Process;
  7. use Symfony\Component\Process\Exception\ProcessFailedException;
  8. use Carbon\Carbon;
  9.  
  10. class MysqlDump extends Command
  11. {
  12. /**
  13. * The name and signature of the console command.
  14. *
  15. * @var string
  16. */
  17. protected $signature = 'db:dump';
  18.  
  19. /**
  20. * The console command description.
  21. *
  22. * @var string
  23. */
  24. protected $description = 'Dump the mysql database api in file storage';
  25.  
  26. /**
  27. * The directory name for dump storage - params from config
  28. * @var string
  29. */
  30. protected $directory;
  31.  
  32. /**
  33. * Max file instorage for rotation - params from config
  34. * @var int
  35. */
  36. protected $max;
  37.  
  38. /**
  39. * Create a new command instance.
  40. *
  41. * @return void
  42. */
  43. public function __construct()
  44. {
  45. parent::__construct();
  46. $this->directory = config('dump.storage');
  47. $this->max = config('dump.max') ?? 5;
  48. }
  49.  
  50. /**
  51. * Execute the console command.
  52. *
  53. * @return mixed
  54. */
  55. public function handle()
  56. {
  57. $command = $this->generateCommand();
  58. $this->process = new Process($command);
  59. $this->process->run();
  60.  
  61. if (!$this->process->isSuccessful()) {
  62. throw new ProcessFailedException($this->process);
  63. }
  64. $this->rotate();
  65. $this->info('The database dumped!');
  66. }
  67.  
  68. public function rotate () {
  69. $f = new \FilesystemIterator($this->directory, \FilesystemIterator::SKIP_DOTS);
  70. if (iterator_count($f) > $this->max) {
  71. $stack = [];
  72. foreach ($f as $key => $value) {
  73. $stack[] = $key;
  74. }
  75. rsort($stack);
  76. $filesToDelete = array_slice($stack, $this->max, null, true);
  77. if (!empty($filesToDelete)) {
  78. foreach ($filesToDelete as $file) {
  79. unlink($file);
  80. }
  81. }
  82. }
  83. }
  84.  
  85. public function generateCommand() {
  86. $db = env('DB_DATABASE');
  87. $pass = env('DB_PASSWORD');
  88. $user = env('DB_USERNAME');
  89. $host = env('DB_HOST');
  90. if (!is_dir($this->directory)) {
  91. $this->info('The dump storage directory is not set, please add a dumps directory in database root directory!');
  92. exit;
  93. }
  94. $prefix = Carbon::now()->format('d-m-Y_H:i:s');
  95. $filename = sprintf('%s/%s_%s', $this->directory, $prefix, config('dump.filename'));
  96. $archive = basename($filename);
  97. return <<<EOF
  98. mysqldump -h$host -u$user -p$pass $db > $filename;
  99. tar cfz database/dumps/$archive.tar.gz database/dumps/$archive;
  100. rm $filename;
  101. EOF;
  102. }
  103. }
Add Comment
Please, Sign In to add comment