Skip to content

Commit a669499

Browse files
authored
Merge branch 'main' into mongo-operators
2 parents 4bde754 + 66e3e23 commit a669499

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

src/Database/Document.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,11 @@ public function __construct(array $input = [])
4646
}
4747

4848
foreach ($value as $childKey => $child) {
49-
if ((isset($child['$id']) || isset($child['$collection'])) && (!$child instanceof self)) {
49+
// An array value is either a list of nested sub-documents or a list of
50+
// plain items (dates, numbers, strings): wrap the former, leave the latter.
51+
// is_array() tells them apart and avoids array-accessing a non-array
52+
// value (e.g. a UTCDateTime), which would otherwise fatal.
53+
if (\is_array($child) && (isset($child['$id']) || isset($child['$collection']))) {
5054
$value[$childKey] = new self($child);
5155
}
5256
}

tests/e2e/Adapter/Scopes/DocumentTests.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6123,6 +6123,42 @@ public function testDateTimeDocument(): void
61236123
$database->deleteCollection($collection);
61246124
}
61256125

6126+
public function testDateTimeArrayDocument(): void
6127+
{
6128+
/** @var Database $database */
6129+
$database = $this->getDatabase();
6130+
6131+
$collection = 'datetime_array_doc';
6132+
$database->createCollection($collection);
6133+
$this->assertEquals(true, $database->createAttribute($collection, 'dates', Database::VAR_DATETIME, 0, false, null, false, true, null, [], ['datetime']));
6134+
6135+
$d1 = '2000-01-01T10:00:00.000+00:00';
6136+
$d2 = '2001-02-03T05:06:07.000+00:00';
6137+
6138+
$database->createDocument($collection, new Document([
6139+
'$id' => 'doc1',
6140+
'$permissions' => [Permission::read(Role::any()), Permission::update(Role::any())],
6141+
'dates' => [$d1, $d2],
6142+
]));
6143+
6144+
// Regression: reading a datetime (object) array used to throw in Mongo with
6145+
// "Cannot use object of type MongoDB\BSON\UTCDateTime as array" because the
6146+
// Document constructor tried to array-access non-array elements.
6147+
$doc = $database->getDocument($collection, 'doc1');
6148+
$dates = $doc->getAttribute('dates');
6149+
$this->assertIsArray($dates);
6150+
$this->assertCount(2, $dates);
6151+
$this->assertEquals($d1, $dates[0]);
6152+
$this->assertEquals($d2, $dates[1]);
6153+
6154+
// Same values must round-trip through find()
6155+
$found = $database->find($collection, [Query::equal('$id', ['doc1'])]);
6156+
$this->assertCount(1, $found);
6157+
$this->assertEquals([$d1, $d2], $found[0]->getAttribute('dates'));
6158+
6159+
$database->deleteCollection($collection);
6160+
}
6161+
61266162
public function testInvalidCreatedAndUpdatedAtThrowStructureException(): void
61276163
{
61286164
/** @var Database $database */

0 commit comments

Comments
 (0)