diff --git a/src/Indexer.php b/src/Indexer.php index ddb1166..fd4681f 100644 --- a/src/Indexer.php +++ b/src/Indexer.php @@ -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); @@ -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) { diff --git a/tests/IndexerTest.php b/tests/IndexerTest.php index 677cc98..92527fa 100644 --- a/tests/IndexerTest.php +++ b/tests/IndexerTest.php @@ -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__);