BSONDocumentTest.php 1.75 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Tests;

5
use MongoDB\Model\BSONArray;
6 7 8 9 10
use MongoDB\Model\BSONDocument;
use ArrayObject;

class BSONDocumentTest extends TestCase
{
11 12 13 14 15 16 17
    public function testConstructorDefaultsToPropertyAccess()
    {
        $document = new BSONDocument(['foo' => 'bar']);
        $this->assertEquals(ArrayObject::ARRAY_AS_PROPS, $document->getFlags());
        $this->assertSame('bar', $document->foo);
    }

18 19 20 21 22 23 24 25
    public function testBsonSerializeCastsToObject()
    {
        $data = [0 => 'foo', 2 => 'bar'];

        $document = new BSONDocument($data);
        $this->assertSame($data, $document->getArrayCopy());
        $this->assertEquals((object) [0 => 'foo', 2 => 'bar'], $document->bsonSerialize());
    }
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    public function testJsonSerialize()
    {
        $document = new BSONDocument([
            'foo' => 'bar',
            'array' => new BSONArray([1, 2, 3]),
            'object' => new BSONDocument([1, 2, 3]),
            'nested' => new BSONDocument([new BSONDocument([new BSONDocument])]),
        ]);

        $expectedJson = '{"foo":"bar","array":[1,2,3],"object":{"0":1,"1":2,"2":3},"nested":{"0":{"0":{}}}}';

        $this->assertSame($expectedJson, json_encode($document));
    }

    public function testJsonSerializeCastsToObject()
    {
        $data = [0 => 'foo', 2 => 'bar'];

        $document = new BSONDocument($data);
        $this->assertSame($data, $document->getArrayCopy());
        $this->assertEquals((object) [0 => 'foo', 2 => 'bar'], $document->jsonSerialize());
    }

50 51 52 53 54 55 56 57
    public function testSetState()
    {
        $data = ['foo' => 'bar'];

        $document = BSONDocument::__set_state($data);
        $this->assertInstanceOf('MongoDB\Model\BSONDocument', $document);
        $this->assertSame($data, $document->getArrayCopy());
    }
58
}