Skip to content

Commit afb7487

Browse files
committed
PHPLIB-74: Model classes for BSON array and document
1 parent 23e8e8e commit afb7487

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

src/Model/BSONArray.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
namespace MongoDB\Model;
4+
5+
use MongoDB\BSON\Serializable;
6+
use MongoDB\BSON\Unserializable;
7+
use ArrayObject;
8+
9+
/**
10+
* Model class for a BSON array.
11+
*
12+
* The internal data will be filtered through array_values() during BSON
13+
* serialization to ensure that it becomes a BSON array.
14+
*
15+
* @api
16+
*/
17+
class BSONArray extends ArrayObject implements Serializable, Unserializable
18+
{
19+
/**
20+
* Serialize the array to BSON.
21+
*
22+
* The array data will be numerically reindexed to ensure that it is stored
23+
* as a BSON array.
24+
*
25+
* @see http://php.net/mongodb-bson-serializable.bsonserialize
26+
* @return array
27+
*/
28+
public function bsonSerialize()
29+
{
30+
return array_values($this->getArrayCopy());
31+
}
32+
33+
/**
34+
* Unserialize the document to BSON.
35+
*
36+
* @see http://php.net/mongodb-bson-unserializable.bsonunserialize
37+
* @param array $data Array data
38+
*/
39+
public function bsonUnserialize(array $data)
40+
{
41+
self::__construct($data);
42+
}
43+
}

src/Model/BSONDocument.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace MongoDB\Model;
4+
5+
use MongoDB\BSON\Serializable;
6+
use MongoDB\BSON\Unserializable;
7+
use ArrayObject;
8+
9+
/**
10+
* Model class for a BSON document.
11+
*
12+
* The internal data will be cast to an object during BSON serialization to
13+
* ensure that it becomes a BSON document.
14+
*
15+
* @api
16+
*/
17+
class BSONDocument extends ArrayObject implements Serializable, Unserializable
18+
{
19+
/**
20+
* Serialize the document to BSON.
21+
*
22+
* @see http://php.net/mongodb-bson-serializable.bsonserialize
23+
* @return object
24+
*/
25+
public function bsonSerialize()
26+
{
27+
return (object) $this->getArrayCopy();
28+
}
29+
30+
/**
31+
* Unserialize the document to BSON.
32+
*
33+
* @see http://php.net/mongodb-bson-unserializable.bsonunserialize
34+
* @param array $data Array data
35+
*/
36+
public function bsonUnserialize(array $data)
37+
{
38+
self::__construct($data, ArrayObject::ARRAY_AS_PROPS);
39+
}
40+
}

0 commit comments

Comments
 (0)