Skip to content
Merged
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
2 changes: 1 addition & 1 deletion src/Database/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -4911,7 +4911,7 @@ public function getDocument(string $collection, string $id, array $queries = [],
}

if (empty($id)) {
return new Document();
return $this->createDocumentInstance($collection, []);
}

$collection = $this->silent(fn () => $this->getCollection($collection));
Expand Down
54 changes: 54 additions & 0 deletions tests/unit/EmptyDocumentTypeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;
use Utopia\Cache\Adapter\Memory as CacheMemory;
use Utopia\Cache\Cache;
use Utopia\Database\Adapter\Memory as DatabaseMemory;
use Utopia\Database\Database;
use Utopia\Database\Document;

class TypedUser extends Document
{
}

class EmptyDocumentTypeTest extends TestCase
{
/**
* A caller that passes the type hint of the mapped class along (an HTTP
* resource returning the current user, say) must be able to rely on every
* empty result being that class, including the one for an empty id, which
* short-circuits before the collection is even looked up.
*/
public function testEmptyIdReturnsTheMappedDocumentType(): void
{
$database = new Database(new DatabaseMemory(), new Cache(new CacheMemory()));
$database
->setDatabase('utopiaTests')
->setNamespace('empty_type_' . \uniqid());
$database->create();
$database->createCollection('users');
$database->setDocumentType('users', TypedUser::class);

$empty = $database->getDocument('users', '');

$this->assertInstanceOf(TypedUser::class, $empty);
$this->assertTrue($empty->isEmpty());

$missing = $database->getDocument('users', 'nobody');

$this->assertInstanceOf(TypedUser::class, $missing);
$this->assertTrue($missing->isEmpty());
}

public function testEmptyIdOnAnUnmappedCollectionStaysAPlainDocument(): void
{
$database = new Database(new DatabaseMemory(), new Cache(new CacheMemory()));

$empty = $database->getDocument('anything', '');

$this->assertSame(Document::class, $empty::class);
$this->assertTrue($empty->isEmpty());
}
}
Loading