Skip to content
This repository has been archived by the owner on Jul 31, 2018. It is now read-only.

Commit

Permalink
Adds onInsert callback to reindex() static call. (#87)
Browse files Browse the repository at this point in the history
* Allows the usage of a callback in reindex() static call to access exactly which entity is being indexed to Algolia

* Improves efficiency of onInsert callback

* Actually updates the README. My bad.
  • Loading branch information
GiamPy5 authored and maxiloc committed Nov 9, 2016
1 parent 363f1b2 commit 5d91565
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,17 @@ To keep settings that you set on the Algolia dashboard when reindexing and setti
Contact::reindex(true, true, true);
```

To implement a callback that gets called everytime a batch of entities is indexed:

```php
Contact::reindex(true, true, false, function ($entities)
{
foreach ($entities as $entity)
{
var_dump($entity->id); // Contact::$id
}
});
```

### Clearing an Index

Expand Down
15 changes: 12 additions & 3 deletions src/AlgoliaEloquentTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ trait AlgoliaEloquentTrait
* @param bool $setSettings
* @param bool $mergeOldSettings
*/
public function _reindex($safe = true, $setSettings = true, $mergeOldSettings = false)
public function _reindex($safe = true, $setSettings = true, $mergeOldSettings = false, \Closure $onInsert = null)
{
/** @var \AlgoliaSearch\Laravel\ModelHelper $modelHelper */
$modelHelper = App::make('\AlgoliaSearch\Laravel\ModelHelper');
Expand All @@ -31,18 +31,27 @@ public function _reindex($safe = true, $setSettings = true, $mergeOldSettings =
$this->_setSettings($setToTmpIndices, $mergeOldSettings);
}

static::chunk(100, function ($models) use ($indicesTmp, $modelHelper) {
static::chunk(100, function ($models) use ($indicesTmp, $modelHelper, $onInsert) {
/** @var \AlgoliaSearch\Index $index */
foreach ($indicesTmp as $index) {
$records = [];
$records = [];
$recordsAsEntity = [];

foreach ($models as $model) {
if ($modelHelper->indexOnly($model, $index->indexName)) {
$records[] = $model->getAlgoliaRecordDefault($index->indexName);

if ($onInsert && is_callable($onInsert)) {
$recordsAsEntity[] = $model;
}
}
}

$index->addObjects($records);

if ($onInsert && is_callable($onInsert)) {
call_user_func_array($onInsert, [$recordsAsEntity]);
}
}

});
Expand Down

0 comments on commit 5d91565

Please sign in to comment.