Skip to content

Commit

Permalink
Merge pull request #35 from xp-forge/refactor/properties-by-ref
Browse files Browse the repository at this point in the history
Return document properties by reference
  • Loading branch information
thekid authored Aug 9, 2023
2 parents 735b84a + 62647de commit 497259b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
17 changes: 12 additions & 5 deletions src/main/php/com/mongodb/Document.class.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php namespace com\mongodb;

use ArrayAccess, Traversable, IteratorAggregate, ReturnTypeWillChange;
use lang\Value;
use lang\{Value, IndexOutOfBoundsException};
use util\Objects;

class Document implements Value, ArrayAccess, IteratorAggregate {
Expand All @@ -28,14 +28,21 @@ public function offsetExists($name) {
}

/**
* Read access overloading
* Read access overloading. Returns a reference!
*
* @param string $name
* @return bool
* @return var
* @throws lang.IndexOutOfBoundsException
*/
#[ReturnTypeWillChange]
public function offsetGet($name) {
return $this->properties[$name];
public function &offsetGet($name) {

// Double-check with array_key_exists() should the property be null.
if (isset($this->properties[$name]) || array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}

throw new IndexOutOfBoundsException('Undefined property "'.$name.'"');
}

/**
Expand Down
31 changes: 29 additions & 2 deletions src/test/php/com/mongodb/unittest/DocumentTest.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,14 @@ public function read_offset() {
Assert::equals('value', $fixture['exists']);
}

#[Test, Expect(IndexOutOfBoundsException::class)]
public function read_non_exstant_offset() {
#[Test]
public function read_null_offset() {
$fixture= new Document(['exists' => null]);
Assert::equals(null, $fixture['exists']);
}

#[Test, Expect(class: IndexOutOfBoundsException::class, message: 'Undefined property "absent"')]
public function read_non_existant_offset() {
$fixture= new Document(['exists' => 'value']);
$r= $fixture['absent'];
}
Expand Down Expand Up @@ -87,4 +93,25 @@ public function delete_offset() {
public function string_representation($fields, $expected) {
Assert::equals($expected, (new Document($fields))->toString());
}

#[Test]
public function sort_offset_array() {
$fixture= new Document(['list' => [1, 3, 2]]);
sort($fixture['list']);
Assert::equals([1, 2, 3], $fixture['list']);
}

#[Test]
public function append_to_offset_array() {
$fixture= new Document(['list' => [1, 2, 3]]);
$fixture['list'][]= 4;
Assert::equals([1, 2, 3, 4], $fixture['list']);
}

#[Test]
public function set_offset_array_key() {
$fixture= new Document(['properties' => ['color' => 'green']]);
$fixture['properties']['price']= 12.99;
Assert::equals(['color' => 'green', 'price' => 12.99], $fixture['properties']);
}
}

0 comments on commit 497259b

Please sign in to comment.