From 682c2e0b8474acfca1953eaca321f6f9bb0245f0 Mon Sep 17 00:00:00 2001 From: shimon Date: Thu, 11 Sep 2025 13:51:49 +0300 Subject: [PATCH] Refactor document ID assignment in Client class to ensure UUID generation is only applied when necessary This update modifies the document ID assignment logic in the Client class to check for existing IDs before generating a new UUID. Additionally, it corrects the expected length of UUIDs in the MongoTest class, ensuring consistency in ID handling across tests. --- src/Client.php | 10 +++++++--- tests/MongoTest.php | 6 +++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Client.php b/src/Client.php index 74ba939145..547b7515a3 100644 --- a/src/Client.php +++ b/src/Client.php @@ -141,7 +141,7 @@ class Client { return Uuid::uuid7()->toString(); } - + /** * Send a raw string query to connection. * @param string $qry @@ -476,7 +476,9 @@ class Client $docObj->{$key} = $value; } - $docObj->_id ??= $this->createUuid(); + if (!isset($docObj->_id) || $docObj->_id === '' || $docObj->_id === null) { + $docObj->_id = $this->createUuid(); + } $this->query(array_merge([ self::COMMAND_INSERT => $collection, @@ -497,7 +499,9 @@ class Client $docObj->{$key} = $value; } - $docObj->_id ??= $this->createUuid(); + if (!isset($docObj->_id) || $docObj->_id === '' || $docObj->_id === null) { + $docObj->_id = $this->createUuid(); + } $docObjs[] = $docObj; } diff --git a/tests/MongoTest.php b/tests/MongoTest.php index aba9be3653..d0fe69898c 100644 --- a/tests/MongoTest.php +++ b/tests/MongoTest.php @@ -62,17 +62,17 @@ class MongoTest extends TestCase ); $id = (string)$doc['_id']; - self::assertEquals(24, strlen($id)); + self::assertEquals(36, strlen($id)); $doc = $this->getDatabase()->find('movies', ['name' => 'Armageddon'])->cursor->firstBatch ?? []; self::assertCount(1, $doc); - $doc = $this->getDatabase()->find('movies', ['_id' => new ObjectId($id)])->cursor->firstBatch ?? []; + $doc = $this->getDatabase()->find('movies', ['_id' => $id])->cursor->firstBatch ?? []; self::assertCount(1, $doc); $doc = $this->getDatabase()->insert('movies', ['9 Monkeys']); $id = (string)$doc['_id']; - self::assertEquals(24, strlen($id)); + self::assertEquals(36, strlen($id)); $doc = $this->getDatabase()->insert( 'movies',