Skip to content

Commit fd291de

Browse files
authored
Merge pull request #57 from xp-forge/feature/document-create
Add Document::create() which creates a document with an object ID
2 parents 7018967 + bc7dafc commit fd291de

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/main/php/com/mongodb/Document.class.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ class Document implements Value, ArrayAccess, IteratorAggregate {
1010
/** @param [:var] */
1111
public function __construct($properties= []) { $this->properties= $properties; }
1212

13+
/** @param [:var]|self $from */
14+
public static function create($from= []): self {
15+
return new self(['_id' => ObjectId::create()] + ($from instanceof self
16+
? $from->properties
17+
: (array)$from
18+
));
19+
}
20+
1321
/** @return string|com.mongodb.ObjectId */
1422
public function id() { return $this->properties['_id'] ?: null; }
1523

src/test/php/com/mongodb/unittest/DocumentTest.class.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,4 +114,35 @@ public function set_offset_array_key() {
114114
$fixture['properties']['price']= 12.99;
115115
Assert::equals(['color' => 'green', 'price' => 12.99], $fixture['properties']);
116116
}
117+
118+
#[Test]
119+
public function create() {
120+
Assert::instance(ObjectId::class, Document::create()->id());
121+
}
122+
123+
#[Test]
124+
public function create_with_properties() {
125+
$fixture= Document::create(['test' => true]);
126+
127+
Assert::instance(ObjectId::class, $fixture->id());
128+
Assert::true($fixture['test']);
129+
}
130+
131+
#[Test]
132+
public function create_passed_id_is_overwritten() {
133+
$id= new ObjectId(self::OID);
134+
$fixture= Document::create(['_id' => $id]);
135+
136+
Assert::notEquals($id, $fixture->id());
137+
}
138+
139+
#[Test]
140+
public function create_copies_document() {
141+
$original= new Document(['_id' => new ObjectId(self::OID), 'test' => true]);
142+
$fixture= Document::create($original);
143+
$original['test']= false;
144+
145+
Assert::notEquals($original->id(), $fixture->id());
146+
Assert::true($fixture['test']);
147+
}
117148
}

0 commit comments

Comments
 (0)