Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent Aggregates that use the same Models from registering multiple observers #239

Merged
merged 8 commits into from
Sep 6, 2021
17 changes: 17 additions & 0 deletions src/Searchable/AggregatorObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,23 @@ public function setAggregator(string $aggregator, array $models): void
}
}

/**
* Set multiple aggregators.
*
* @param string[] $aggregators
* @param string $model
*
* @return void
*/
public function setAggregators(array $aggregators, string $model): void
{
if (! array_key_exists($model, $this->aggregators)) {
$this->aggregators[$model] = [];
}

$this->aggregators[$model] = $aggregators;
}

/**
* {@inheritdoc}
*/
Expand Down
41 changes: 41 additions & 0 deletions src/Searchable/Aggregators.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

/**
* This file is part of Scout Extended.
*
* (c) Algolia Team <contact@algolia.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Algolia\ScoutExtended\Searchable;

class Aggregators extends Aggregator
{
/**
* Boot multiple aggregators.
*
* @return void
*/
public static function bootSearchables(array $searchables): void
{
(new static)->registerSearchableMacros();

$models = [];

foreach ($searchables as $searchable) {
foreach ((new $searchable)->getModels() as $model) {
$models[$model][] = $searchable;
JayBizzle marked this conversation as resolved.
Show resolved Hide resolved
}
}

foreach ($models as $model => $searchables) {
$observer = tap(app(AggregatorObserver::class))->setAggregators($searchables, $model);

$model::observe($observer);
}
}
}