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

Merge pull request #130 from alcaeus/mongoid-json-serializable

Add implementation of JsonSerializable to MongoId
Andreas 9 лет назад
Родитель
Сommit
c5e8814e82
3 измененных файлов с 16 добавлено и 1 удалено
  1. 2 0
      CHANGELOG-1.0.md
  2. 11 1
      lib/Mongo/MongoId.php
  3. 3 0
      tests/Alcaeus/MongoDbAdapter/Mongo/MongoIdTest.php

+ 2 - 0
CHANGELOG-1.0.md

@@ -12,6 +12,8 @@ milestone.
 
  * [#126](https://github.com/alcaeus/mongo-php-adapter/pull/126) fixes a class
  name that was improperly capitalized.
+ * [#130](https://github.com/alcaeus/mongo-php-adapter/pull/130) fixes JSON
+ serialization of `MongoId` objects.
 
 1.0.5 (2016-07-03)
 ------------------

+ 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()