Skip to content

Commit

Permalink
Merge pull request #564 from pinkary-project/feat/sync-missing-hashta…
Browse files Browse the repository at this point in the history
…gs-command

feat(hashtags): add SyncMissingQuestionHashtags command
  • Loading branch information
nunomaduro authored Sep 6, 2024
2 parents 27cb3e9 + 86285e3 commit 9d8ab47
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
69 changes: 69 additions & 0 deletions app/Console/Commands/SyncMissingQuestionHashtags.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\EventActions\UpdateQuestionHashtags;
use App\Models\Question;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;

final class SyncMissingQuestionHashtags extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:sync-missing-hashtags {runtime=28 : The maximum execution time of the command}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Sync missing question hashtags';

/**
* Execute the console command.
*/
public function handle(): void
{
$runtime = (int) $this->argument('runtime');
$runUntil = now()->addSeconds($runtime);
$halted = false;

$questions = Question::query()
->whereDoesntHave('hashtags')
->where(fn (Builder $where): Builder => $where
->where('content', 'like', '%#%')
->orWhere('answer', 'like', '%#%')
)
->lazyByIdDesc();

$bar = $this->output->createProgressBar(count($questions));

$bar->start();

foreach ($questions as $question) {
if (now()->isAfter($runUntil)) {
$halted = true;
break;
}

(new UpdateQuestionHashtags($question))->handle();

$bar->advance();
}

if ($halted) {
$this->newLine();
$this->info('Halting process to limit runtime.');

return;
}

$bar->finish();
}
}
25 changes: 25 additions & 0 deletions tests/Console/SyncMissingQuestionHashtagsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

it('syncs hashtag relations for questions that are missing hashtags', function () {
/** @var Tests\TestCase $this */
$withHashtags = App\Models\Question::factory(10)->create(['answer' => 'has a #hashtag']);
$withoutHashtags = App\Models\Question::factory(10)->create(['answer' => 'no hashtags here']);

Illuminate\Support\Facades\DB::table('hashtag_question')->truncate();

$this->artisan('app:sync-missing-hashtags')->assertSuccessful();

$withHashtags->load('hashtags');
$withoutHashtags->load('hashtags');

expect($withHashtags->every(
fn (App\Models\Question $question): bool => $question->hashtags->pluck('name')->all() === ['hashtag'])
)
->toBeTrue();
expect($withoutHashtags->every(
fn (App\Models\Question $question): bool => $question->hashtags->isEmpty())
)
->toBeTrue();
});

0 comments on commit 9d8ab47

Please sign in to comment.