Skip to content

Commit

Permalink
Fires event models imported in aggregators
Browse files Browse the repository at this point in the history
  • Loading branch information
nunomaduro committed Nov 16, 2018
1 parent d71674c commit 29c56a6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
13 changes: 12 additions & 1 deletion src/Console/Commands/ImportCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@
use Laravel\Scout\Searchable;
use Illuminate\Console\Command;
use Algolia\ScoutExtended\Algolia;
use Laravel\Scout\Events\ModelsImported;
use Illuminate\Contracts\Events\Dispatcher;
use Algolia\ScoutExtended\Helpers\SearchableFinder;
use Algolia\ScoutExtended\Searchable\ObjectIdEncrypter;

final class ImportCommand extends Command
{
Expand All @@ -33,13 +36,21 @@ final class ImportCommand extends Command
/**
* {@inheritdoc}
*/
public function handle(SearchableFinder $searchableFinder): void
public function handle(Dispatcher $events, SearchableFinder $searchableFinder): void
{
foreach ($searchableFinder->fromCommand($this) as $searchable) {
$this->call('scout:flush', ['searchable' => $searchable]);

$events->listen(ModelsImported::class, function ($event) use ($searchable) {
$last = ObjectIdEncrypter::encrypt($event->models->last());

$this->line('<comment>Imported ['.$searchable.'] models up to ID:</comment> '.$last);
});

$searchable::makeAllSearchable();

$events->forget(ModelsImported::class);

$this->output->success('All ['.$searchable.'] records have been imported.');
}
}
Expand Down
9 changes: 7 additions & 2 deletions src/Searchable/Aggregator.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Illuminate\Support\Str;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Events\ModelsImported;
use Illuminate\Database\Eloquent\SoftDeletes;
use Algolia\ScoutExtended\Contracts\SearchableCountableContract;
use Algolia\ScoutExtended\Exceptions\ModelNotDefinedInAggregatorException;
Expand Down Expand Up @@ -169,9 +170,13 @@ public static function makeAllSearchable()
$instance->newQuery()->when($softDeletes, function ($query) {
$query->withTrashed();
})->orderBy($instance->getKeyName())->chunk(config('scout.chunk.searchable', 500), function ($models) {
$models->map(function ($model) {
$models = $models->map(function ($model) {
return static::create($model);
})->filter->shouldBeSearchable()->searchable();
})->filter->shouldBeSearchable();

$models->searchable();

event(new ModelsImported($models));
});
}
}
Expand Down

0 comments on commit 29c56a6

Please sign in to comment.