Advertisement
Guest User

Untitled

a guest
Feb 9th, 2017
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Console\Commands;
  4.  
  5. use Aws\S3\MultipartUploader;
  6. use Aws\Exception\MultipartUploadException;
  7. use Illuminate\Console\Command;
  8. use Storage;
  9.  
  10. class BackupCRM extends Command
  11. {
  12. /**
  13. * The name and signature of the console command.
  14. *
  15. * @var string
  16. */
  17. protected $signature = 'db:backup {--only-db} {--only-uploads}';
  18.  
  19. /**
  20. * The console command description.
  21. *
  22. * @var string
  23. */
  24. protected $description = 'Backups datatbase and uploads.';
  25.  
  26. /**
  27. * Create a new command instance.
  28. *
  29. * @return void
  30. */
  31. public function __construct()
  32. {
  33. parent::__construct();
  34. }
  35.  
  36. /**
  37. * Execute the console command.
  38. *
  39. * @return mixed
  40. */
  41. public function handle()
  42. {
  43. if ($this->option('only-db')) {
  44. return $this->backupDB(env('DB_USERNAME'), env('DB_PASSWORD'), env('DB_HOST'), env('DB_DATABASE'));
  45. } else if ($this->option('only-uploads')) {
  46. return $this->backupUploads(env('S3_BUCKET'));
  47. } else {
  48. $this->backupDB(env('DB_USERNAME'), env('DB_PASSWORD'), env('DB_HOST'), env('DB_DATABASE'));
  49. $this->backupUploads(env('S3_BUCKET'));
  50. return $this->info('Full backup completed!');
  51. }
  52. }
  53.  
  54. protected function backupDB($user, $password, $host, $db)
  55. {
  56. $filePrefix = date('m-d-y-h:i:s');
  57. $fileSql = $filePrefix.'file.sql';
  58.  
  59. exec('mysqldump --result-file=storage/app/'.$fileSql.' --user='.$user.' --password='.$password.' --host='.$host.' '.$db);
  60. exec('gzip storage/app/'.$fileSql);
  61. Storage::disk('s3')->put('database-backups/'. date("Y") . '/' . date("m") . '/'.$filePrefix.'file.sql.gz' , fopen('storage/app/'.$filePrefix.'file.sql.gz', 'r+'));
  62. Storage::delete($filePrefix.'file.sql.gz');
  63. return $this->info('Database backup completed!');
  64. }
  65.  
  66. protected function backupUploads($bucket)
  67. {
  68. $uploads = date('m-d-y-h:i:s').'uploads.tar.gz';
  69. exec('tar -zcf storage/app/'.$uploads.' public/uploads/');
  70.  
  71. $disk = Storage::disk('s3');
  72. $fromPath = 'storage/app/'.$uploads;
  73. $toPath = 'uploads-backups/'. date("Y") . '/' . date("m") . '/'.$uploads;
  74. $uploader = new MultipartUploader($disk->getDriver()->getAdapter()->getClient(), $fromPath, [
  75. 'bucket' => $bucket,
  76. 'key' => $toPath,
  77. ]);
  78.  
  79. try {
  80. $result = $uploader->upload();
  81. $this->info('Uploads backup completed!');
  82. Storage::delete($uploads);
  83. } catch (MultipartUploadException $e) {
  84. echo $e->getMessage();
  85. }
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement