HashtagRelatedGenerate.php 2.3 KB

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