Skip to content

Serializable returning BSON class #496

@rbro

Description

@rbro

This is related to #495 that I submitted earlier. Because I couldn't extend MongoDB\BSON\UTCDateTime, I attempted the below using MongoDB\BSON\Serializable to return an object of type MongoDB\BSON\UTCDateTime, but it's throwing an error that bsonSerialize must return either an array or stdClass. Could bsonSerialize be updated to allow a BSON class to be returned?

<?php
class abc implements MongoDB\BSON\Serializable
{
	private $o_object = null;

	public function __construct($milliseconds)
	{
		$this->o_object = new MongoDB\BSON\UTCDatetime($milliseconds);
	}

	function bsonSerialize()
	{
		return $this->o_object;
	}
}

$collection = (new MongoDB\Client)->example->users;

$collection->insertOne(array(
	'abc' => new abc(100),
));

The error is:

Uncaught MongoDB\Driver\Exception\UnexpectedValueException: Expected abc::bsonSerialize() to return an array or stdClass, MongoDB\BSON\UTCDateTime given

Thanks for your help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions