diff --git a/src/MongoDbEventStoreAdapter.php b/src/MongoDbEventStoreAdapter.php index a4adc36..ff27257 100644 --- a/src/MongoDbEventStoreAdapter.php +++ b/src/MongoDbEventStoreAdapter.php @@ -157,7 +157,7 @@ public function appendTo(StreamName $streamName, Iterator $streamEvents) } catch (\MongoDB\Driver\Exception\BulkWriteException $e) { $code = isset($e->getWriteResult()->getWriteErrors()[0]) ? $e->getWriteResult()->getWriteErrors()[0]->getCode() - : 0; + : $e->getCode(); if (\in_array($code, [11000, 11001, 12582], true)) { throw new ConcurrencyException('At least one event with same version exists already', 0, $e); diff --git a/tests/MongoDbEventStoreAdapterTest.php b/tests/MongoDbEventStoreAdapterTest.php index cf5b47d..58ec097 100644 --- a/tests/MongoDbEventStoreAdapterTest.php +++ b/tests/MongoDbEventStoreAdapterTest.php @@ -17,6 +17,7 @@ use Prooph\Common\Messaging\NoOpMessageConverter; use Prooph\EventStore\Adapter\MongoDb\Exception\RuntimeAdapterException; use Prooph\EventStore\Adapter\MongoDb\MongoDbEventStoreAdapter; +use Prooph\EventStore\Exception\ConcurrencyException; use Prooph\EventStore\Stream\Stream; use Prooph\EventStore\Stream\StreamName; use ProophTest\EventStore\Mock\UserCreated; @@ -541,6 +542,37 @@ public function it_writes_to_different_streams_in_one_transaction_if_they_exists $this->assertEquals(2, $this->client->selectCollection($dbName, 'another_test_stream')->countDocuments()); } + /** + * @test + */ + public function it_throws_concurrency_exception_on_duplicate_key_error(): void + { + $dbName = TestUtil::getDatabaseName(); + + $this->adapter = new MongoDbEventStoreAdapter( + new FQCNMessageFactory(), + new NoOpMessageConverter(), + $this->client, + $dbName, + [ + 'Prooph\Model\User' => 'test_collection_name', + ] + ); + + $testStream = $this->getTestStream(); + + $this->adapter->beginTransaction(); + + $this->adapter->create($testStream); + + $this->expectException(ConcurrencyException::class); + $this->expectExceptionMessage('At least one event'); + + $this->adapter->appendTo($testStream->streamName(), $testStream->streamEvents()); + + $this->adapter->commit(); + } + /** * @test */