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

Fix inserts with array objects

Andreas Braun 6 лет назад
Родитель
Сommit
e41f814417

+ 2 - 2
lib/Mongo/MongoCollection.php

@@ -999,12 +999,12 @@ class MongoCollection
      */
     private function ensureDocumentHasMongoId(&$document)
     {
-        if (is_array($document)) {
+        if (is_array($document) || $document instanceof ArrayObject) {
             if (! isset($document['_id'])) {
                 $document['_id'] = new \MongoId();
             }
 
-            $this->checkKeys($document);
+            $this->checkKeys((array) $document);
 
             return $document['_id'];
         } elseif (is_object($document)) {

+ 16 - 0
tests/Alcaeus/MongoDbAdapter/Mongo/MongoCollectionTest.php

@@ -2,9 +2,11 @@
 
 namespace Alcaeus\MongoDbAdapter\Tests\Mongo;
 
+use ArrayObject;
 use MongoDB\BSON\Regex;
 use MongoDB\Driver\ReadPreference;
 use Alcaeus\MongoDbAdapter\Tests\TestCase;
+use MongoId;
 use PHPUnit\Framework\Error\Warning;
 
 /**
@@ -95,6 +97,15 @@ class MongoCollectionTest extends TestCase
         $this->getCollection()->insert($document);
     }
 
+    public function testInsertArrayObjectWithProtectedProperties()
+    {
+        $document = new ArrayObjectWithProtectedProperties(['foo' => 'bar']);
+        $this->getCollection()->insert($document);
+
+        $this->assertInstanceOf('MongoId', $document['_id']);
+        $this->assertEquals(['_id' => $document['_id'], 'foo' => 'bar'], $this->getCollection()->findOne(['_id' => $document['_id']]));
+    }
+
     public function testInsertWithInvalidKey()
     {
         $document = ['*' => 'foo'];
@@ -1991,3 +2002,8 @@ class PrivatePropertiesStub
 {
     private $foo = 'bar';
 }
+
+class ArrayObjectWithProtectedProperties extends ArrayObject
+{
+    protected $something = 'baz';
+}