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

Throw an exception when the Indexer queue is not cleared #42

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/Indexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,18 @@ class Indexer

public function __construct(Client $client, SerializerInterface $serializer, int $bulkMaxSize = 100)
{
// TODO: on the destruct, maybe throw an exception for non empty indexer queues?

$this->client = $client;
$this->bulkMaxSize = $bulkMaxSize ?? 100;
$this->serializer = $serializer;
}

public function __destruct()
{
if ($this->getQueueSize() > 0) {
throw new \RuntimeException(sprintf('%s queue is not empty, you need to call flush() to send documents to Elasticsearch or clear() to empty the queue.', __CLASS__));
}
}

public function scheduleIndex($index, Document $document)
{
$document->setIndex($index instanceof Index ? $index->getName() : $index);
Expand Down Expand Up @@ -104,6 +109,11 @@ public function flush(): ?Bulk\ResponseSet
return $response;
}

public function clear(): void
{
$this->currentBulk = null;
}

public function getQueueSize()
{
if (null === $this->currentBulk) {
Expand Down
24 changes: 24 additions & 0 deletions tests/IndexerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,30 @@ public function testIndexOneDocument(): void
$this->assertEquals('f', $document->getId());
}

public function testIndexDocumentsWithoutFlushingThrowError(): void
{
$indexName = mb_strtolower(__FUNCTION__);
$dto = new TestDTO();
$dto->bar = 'Oops I forgot the flush.';

$indexer = $this->getIndexer();

$indexer->scheduleIndex($indexName, new Document('f', $dto));
$this->assertEquals(1, $indexer->getQueueSize());
$indexer->clear();
$this->assertEquals(0, $indexer->getQueueSize());

$indexer->scheduleIndex($indexName, new Document('f', $dto));
try {
$indexer->__destruct();
$this->assertFalse(true, 'This code should not be accessible.');
} catch (\RuntimeException $exception) {
$this->assertStringContainsString('queue is not empty', $exception->getMessage());
}

$indexer->clear(); // avoid fatal error when the test ends
}

public function testIndexOneDocumentWithMapping(): void
{
$indexName = mb_strtolower(__FUNCTION__);
Expand Down