Просмотр исходного кода

Add implementation of JsonSerializable to MongoId

Vladimir Komissarov 9 лет назад
Родитель
Сommit
fc28859001
2 измененных файлов с 14 добавлено и 1 удалено
  1. 11 1
      lib/Mongo/MongoId.php
  2. 3 0
      tests/Alcaeus/MongoDbAdapter/Mongo/MongoIdTest.php

+ 11 - 1
lib/Mongo/MongoId.php

@@ -20,7 +20,7 @@ if (class_exists('MongoId', false)) {
 use Alcaeus\MongoDbAdapter\TypeInterface;
 use MongoDB\BSON\ObjectID;
 
-class MongoId implements Serializable, TypeInterface
+class MongoId implements Serializable, TypeInterface, JsonSerializable
 {
     /*
      * @var ObjectID
@@ -201,6 +201,16 @@ class MongoId implements Serializable, TypeInterface
     }
 
     /**
+     * @return stdClass
+     */
+    public function jsonSerialize()
+    {
+        $object = new stdClass();
+        $object->{'$id'} = (string) $this->objectID;
+        return $object;
+    }
+
+    /**
      * @param $id
      * @throws MongoException
      */

+ 3 - 0
tests/Alcaeus/MongoDbAdapter/Mongo/MongoIdTest.php

@@ -24,6 +24,9 @@ class MongoIdTest extends TestCase
         $unserialized = unserialize($serialized);
         $this->assertInstanceOf('MongoId', $unserialized);
         $this->assertSame($stringId, (string) $unserialized);
+
+        $json = json_encode($id);
+        $this->assertSame(sprintf('{"$id":"%s"}', $stringId), $json);
     }
 
     public function testCreateWithString()