HashtagRelatedGenerate.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Hashtag;
  5. use App\StatusHashtag;
  6. use App\Models\HashtagRelated;
  7. use App\Services\HashtagRelatedService;
  8. use Illuminate\Contracts\Console\PromptsForMissingInput;
  9. use function Laravel\Prompts\multiselect;
  10. use function Laravel\Prompts\confirm;
  11. class HashtagRelatedGenerate extends Command implements PromptsForMissingInput
  12. {
  13. /**
  14. * The name and signature of the console command.
  15. *
  16. * @var string
  17. */
  18. protected $signature = 'app:hashtag-related-generate {tag}';
  19. /**
  20. * The console command description.
  21. *
  22. * @var string
  23. */
  24. protected $description = 'Command description';
  25. /**
  26. * Prompt for missing input arguments using the returned questions.
  27. *
  28. * @return array
  29. */
  30. protected function promptForMissingArgumentsUsing()
  31. {
  32. return [
  33. 'tag' => 'Which hashtag should we generate related tags for?',
  34. ];
  35. }
  36. /**
  37. * Execute the console command.
  38. */
  39. public function handle()
  40. {
  41. $tag = $this->argument('tag');
  42. $hashtag = Hashtag::whereName($tag)->orWhere('slug', $tag)->first();
  43. if(!$hashtag) {
  44. $this->error('Hashtag not found, aborting...');
  45. exit;
  46. }
  47. $exists = HashtagRelated::whereHashtagId($hashtag->id)->exists();
  48. if($exists) {
  49. $confirmed = confirm('Found existing related tags, do you want to regenerate them?');
  50. if(!$confirmed) {
  51. $this->error('Aborting...');
  52. exit;
  53. }
  54. }
  55. $this->info('Looking up #' . $tag . '...');
  56. $tags = StatusHashtag::whereHashtagId($hashtag->id)->count();
  57. if(!$tags || $tags < 100) {
  58. $this->error('Not enough posts found to generate related hashtags!');
  59. exit;
  60. }
  61. $this->info('Found ' . $tags . ' posts that use that hashtag');
  62. $related = collect(HashtagRelatedService::fetchRelatedTags($tag));
  63. $selected = multiselect(
  64. label: 'Which tags do you want to generate?',
  65. options: $related->pluck('name'),
  66. required: true,
  67. );
  68. $filtered = $related->filter(fn($i) => in_array($i['name'], $selected))->all();
  69. $agg_score = $related->filter(fn($i) => in_array($i['name'], $selected))->sum('related_count');
  70. HashtagRelated::updateOrCreate([
  71. 'hashtag_id' => $hashtag->id,
  72. ], [
  73. 'related_tags' => array_values($filtered),
  74. 'agg_score' => $agg_score,
  75. 'last_calculated_at' => now()
  76. ]);
  77. $this->info('Finished!');
  78. }
  79. }