Parcourir la source

Ensure type conversion for MongoCode objects

Includes a note in README because we can't convert BSON objects back
Andreas Braun il y a 10 ans
Parent
commit
ef91bf61b6
2 fichiers modifiés avec 47 ajouts et 1 suppressions
  1. 17 1
      lib/Mongo/MongoCode.php
  2. 30 0
      tests/Alcaeus/MongoDbAdapter/MongoCodeTest.php

+ 17 - 1
lib/Mongo/MongoCode.php

@@ -13,7 +13,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-class MongoCode
+class MongoCode implements \Alcaeus\MongoDbAdapter\TypeInterface
 {
     /**
      * @var string
@@ -32,6 +32,11 @@ class MongoCode
      */
     public function __construct($code, array $scope = [])
     {
+        if ($code instanceof \MongoDB\BSON\Javascript) {
+            // @todo Use properties from object once they are accessible
+            $code = '';
+        }
+
         $this->code = $code;
         $this->scope = $scope;
     }
@@ -44,4 +49,15 @@ class MongoCode
     {
         return $this->code;
     }
+
+    /**
+     * Converts this MongoCode to the new BSON JavaScript type
+     *
+     * @return \MongoDB\BSON\Javascript
+     * @internal This method is not part of the ext-mongo API
+     */
+    public function toBSONType()
+    {
+        return new \MongoDB\BSON\Javascript($this->code, $this->scope);
+    }
 }

+ 30 - 0
tests/Alcaeus/MongoDbAdapter/MongoCodeTest.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace Alcaeus\MongoDbAdapter\Tests;
+
+/**
+ * @author alcaeus <alcaeus@alcaeus.org>
+ */
+class MongoCodeTest extends TestCase
+{
+    public function testCreate()
+    {
+        $code = new \MongoCode('code', ['scope' => 'bleh']);
+        $this->assertAttributeSame('code', 'code', $code);
+        $this->assertAttributeSame(['scope' => 'bleh'], 'scope', $code);
+
+        $this->assertSame('code', (string) $code);
+
+        $bsonCode = $code->toBSONType();
+        $this->assertInstanceOf('MongoDB\BSON\Javascript', $bsonCode);
+    }
+
+    public function testCreateWithBsonObject()
+    {
+        $bsonCode = new \MongoDB\BSON\Javascript('code', ['scope' => 'bleh']);
+        $code = new \MongoCode($bsonCode);
+
+        $this->assertAttributeSame('', 'code', $code);
+        $this->assertAttributeSame([], 'scope', $code);
+    }
+}