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.
This commit is contained in:
shimon committed 2025-09-11 13:51:49 +03:00
1 parent f25c14e4e3
commit 682c2e0b84
2 files changed
+10 -6

No files matched your search

+7 -3
View File
@@ -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;
}
+3 -3
View File
@@ -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',