Skip to content

Commit c094f99

Browse files
committed
PHPLIB-163: __set_state() for BSON array and document models
1 parent 35aa950 commit c094f99

File tree

4 files changed

+50
-0
lines changed

4 files changed

+50
-0
lines changed

src/Model/BSONArray.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,22 @@
1616
*/
1717
class BSONArray extends ArrayObject implements Serializable, Unserializable
1818
{
19+
/**
20+
* Factory method for var_export().
21+
*
22+
* @see http://php.net/oop5.magic#object.set-state
23+
* @see http://php.net/var-export
24+
* @param array $properties
25+
* @return self
26+
*/
27+
public static function __set_state(array $properties)
28+
{
29+
$array = new static;
30+
$array->exchangeArray($properties);
31+
32+
return $array;
33+
}
34+
1935
/**
2036
* Serialize the array to BSON.
2137
*

src/Model/BSONDocument.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,22 @@ public function __construct($input = [], $flags = ArrayObject::ARRAY_AS_PROPS, $
2929
parent::__construct($input, $flags, $iterator_class);
3030
}
3131

32+
/**
33+
* Factory method for var_export().
34+
*
35+
* @see http://php.net/oop5.magic#object.set-state
36+
* @see http://php.net/var-export
37+
* @param array $properties
38+
* @return self
39+
*/
40+
public static function __set_state(array $properties)
41+
{
42+
$document = new static;
43+
$document->exchangeArray($properties);
44+
45+
return $document;
46+
}
47+
3248
/**
3349
* Serialize the document to BSON.
3450
*

tests/Model/BSONArrayTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,13 @@ public function testBsonSerializeReindexesKeys()
1414
$this->assertSame($data, $array->getArrayCopy());
1515
$this->assertSame(['foo', 'bar'], $array->bsonSerialize());
1616
}
17+
18+
public function testSetState()
19+
{
20+
$data = ['foo', 'bar'];
21+
22+
$array = BSONArray::__set_state($data);
23+
$this->assertInstanceOf('MongoDB\Model\BSONArray', $array);
24+
$this->assertSame($data, $array->getArrayCopy());
25+
}
1726
}

tests/Model/BSONDocumentTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,13 @@ public function testBsonSerializeCastsToObject()
2222
$this->assertSame($data, $document->getArrayCopy());
2323
$this->assertEquals((object) [0 => 'foo', 2 => 'bar'], $document->bsonSerialize());
2424
}
25+
26+
public function testSetState()
27+
{
28+
$data = ['foo' => 'bar'];
29+
30+
$document = BSONDocument::__set_state($data);
31+
$this->assertInstanceOf('MongoDB\Model\BSONDocument', $document);
32+
$this->assertSame($data, $document->getArrayCopy());
33+
}
2534
}

0 commit comments

Comments
 (0)