AvatarDefaultMigration.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Avatar;
  5. use Cache, DB;
  6. use Illuminate\Support\Str;
  7. class AvatarDefaultMigration extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'fix:avatars';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'Replace old svg identicon avatars with default png avatar';
  21. /**
  22. * Create a new command instance.
  23. *
  24. * @return void
  25. */
  26. public function __construct()
  27. {
  28. parent::__construct();
  29. }
  30. /**
  31. * Execute the console command.
  32. *
  33. * @return mixed
  34. */
  35. public function handle()
  36. {
  37. $this->info('Running avatar migration...');
  38. $count = Avatar::whereChangeCount(0)->count();
  39. if($count == 0) {
  40. $this->info('Found no avatars needing to be migrated!');
  41. exit;
  42. }
  43. $bar = $this->output->createProgressBar($count);
  44. $this->info("Found {$count} avatars that may need to be migrated");
  45. Avatar::whereChangeCount(0)->chunk(50, function($avatars) use ($bar) {
  46. foreach($avatars as $avatar) {
  47. if( $avatar->media_path == 'public/avatars/default.png' ||
  48. $avatar->thumb_path == 'public/avatars/default.png' ||
  49. $avatar->media_path == 'public/avatars/default.jpg' ||
  50. $avatar->thumb_path == 'public/avatars/default.jpg'
  51. ) {
  52. continue;
  53. }
  54. if(Str::endsWith($avatar->media_path, '/avatar.svg') == false) {
  55. // do not modify non-default avatars
  56. continue;
  57. }
  58. DB::transaction(function() use ($avatar, $bar) {
  59. if(is_file(storage_path('app/' . $avatar->media_path))) {
  60. @unlink(storage_path('app/' . $avatar->media_path));
  61. }
  62. if(is_file(storage_path('app/' . $avatar->thumb_path))) {
  63. @unlink(storage_path('app/' . $avatar->thumb_path));
  64. }
  65. $avatar->media_path = 'public/avatars/default.jpg';
  66. $avatar->thumb_path = 'public/avatars/default.jpg';
  67. $avatar->change_count = $avatar->change_count + 1;
  68. $avatar->save();
  69. Cache::forget('avatar:' . $avatar->profile_id);
  70. $bar->advance();
  71. });
  72. }
  73. });
  74. $bar->finish();
  75. }
  76. }