Selaa lähdekoodia

Rename methods in TypeConverter

Andreas Braun 10 vuotta sitten
vanhempi
commit
b17a5c25e2

+ 1 - 1
lib/Alcaeus/MongoDbAdapter/AbstractCursor.php

@@ -110,7 +110,7 @@ abstract class AbstractCursor
     {
         $document = $this->ensureIterator()->current();
         if ($document !== null) {
-            $document = TypeConverter::convertObjectToLegacyArray($document);
+            $document = TypeConverter::toLegacy($document);
         }
 
         return $document;

+ 76 - 34
lib/Alcaeus/MongoDbAdapter/TypeConverter.php

@@ -20,31 +20,93 @@ namespace Alcaeus\MongoDbAdapter;
  */
 class TypeConverter
 {
-    public static function convertLegacyArrayToObject($array)
+    /**
+     * Converts a legacy type to the new BSON type
+     *
+     * This method handles type conversion from ext-mongo to ext-mongodb:
+     *  - For all types (MongoId, MongoDate, etc.) it returns the correct BSON
+     *    object instance
+     *  - For arrays and objects it iterates over properties and converts each
+     *    item individually
+     *  - For other types it returns the value unconverted
+     *
+     * @param mixed $value
+     * @return mixed
+     */
+    public static function fromLegacy($value)
     {
-        // TODO: provide actual class once mongodb/mongo-php-library#78 has been merged
-        $result = [];
+        switch (true) {
+            case $value instanceof TypeInterface:
+                return $value->toBSONType();
+            case is_array($value):
+            case is_object($value);
+                $result = [];
 
-        foreach ($array as $key => $value) {
-            $result[$key] = (is_array($value)) ? static::convertLegacyArrayToObject($value) : static::convertToBSONType($value);
-        }
+                foreach ($value as $key => $item) {
+                    $result[$key] = self::fromLegacy($item);
+                }
 
-        return self::ensureCorrectType($result);
+                return self::ensureCorrectType($result);
+            default:
+                return $value;
+        }
     }
 
-    public static function convertObjectToLegacyArray($object)
+    /**
+     * Converts a BSON type to the legacy types
+     *
+     * This method handles type conversion from ext-mongodb to ext-mongo:
+     *  - For all instances of \MongoDB\BSON\Type it returns an object of the
+     *    corresponding legacy type (MongoId, MongoDate, etc.)
+     *  - For arrays and objects it iterates over properties and converts each
+     *    item individually
+     *  - For other types it returns the value unconverted
+     *
+     * @param mixed $value
+     * @return mixed
+     */
+    public static function toLegacy($value)
     {
-        $result = [];
+        switch (true) {
+            case $value instanceof \MongoDB\BSON\Type:
+                return self::convertBSONObjectToLegacy($value);
+            case is_array($value):
+            case is_object($value):
+                $result = [];
 
-        foreach ($object as $key => $value) {
-            // TODO: use actual class instead of \stdClass once mongodb/mongo-php-library#78 has been merged
-            $result[$key] = ($value instanceof \stdClass || is_array($value)) ? static::convertObjectToLegacyArray($value) : static::convertToLegacyType($value);
+                foreach ($value as $key => $item) {
+                    $result[$key] = self::toLegacy($item);
+                }
+
+                return $result;
+            default:
+                return $value;
         }
+    }
 
-        return $result;
+    /**
+     * Helper method to find out if an array has numerical indexes
+     *
+     * For performance reason, this method checks the first array index only.
+     * More thorough inspection of the array might be needed.
+     * Note: Returns true for empty arrays to preserve compatibility with empty
+     * lists.
+     *
+     * @param array $array
+     * @return bool
+     */
+    public static function isNumericArray(array $array)
+    {
+        return $array === [] || is_numeric(array_keys($array)[0]);
     }
 
-    public static function convertToLegacyType($value)
+    /**
+     * Converter method to convert a BSON object to its legacy type
+     *
+     * @param \MongoDB\BSON\Type $value
+     * @return mixed
+     */
+    private static function convertBSONObjectToLegacy(\MongoDB\BSON\Type $value)
     {
         switch (true) {
             case $value instanceof \MongoDB\BSON\ObjectID:
@@ -68,26 +130,6 @@ class TypeConverter
         }
     }
 
-    public static function convertToBSONType($value)
-    {
-        switch (true) {
-            case $value instanceof TypeInterface:
-                return $value->toBSONType();
-
-            default:
-                return $value;
-        }
-    }
-
-    /**
-     * @param array $array
-     * @return bool
-     */
-    public static function isNumericArray(array $array)
-    {
-        return $array === [] || is_numeric(array_keys($array)[0]);
-    }
-
     /**
      * Converts all arrays with non-numeric keys to stdClass
      *

+ 18 - 19
lib/Mongo/MongoCollection.php

@@ -170,9 +170,8 @@ class MongoCollection
         ];
 
         // Convert cursor option
-        if (! isset($options['cursor']) || $options['cursor'] === true || $options['cursor'] === []) {
-            // Cursor option needs to be an object convert bools and empty arrays since those won't be handled by TypeConverter
-            $options['cursor'] = new \stdClass;
+        if (! isset($options['cursor'])) {
+            $options['cursor'] = true;
         }
 
         $command += $options;
@@ -224,7 +223,7 @@ class MongoCollection
      */
     public function drop()
     {
-        return TypeConverter::convertObjectToLegacyArray($this->collection->drop());
+        return TypeConverter::toLegacy($this->collection->drop());
     }
 
     /**
@@ -258,7 +257,7 @@ class MongoCollection
     public function insert($a, array $options = [])
     {
         $result = $this->collection->insertOne(
-            TypeConverter::convertLegacyArrayToObject($a),
+            TypeConverter::fromLegacy($a),
             $this->convertWriteConcernOptions($options)
         );
 
@@ -286,7 +285,7 @@ class MongoCollection
     public function batchInsert(array $a, array $options = [])
     {
         $result = $this->collection->insertMany(
-            TypeConverter::convertLegacyArrayToObject($a),
+            TypeConverter::fromLegacy($a),
             $this->convertWriteConcernOptions($options)
         );
 
@@ -322,8 +321,8 @@ class MongoCollection
 
         /** @var \MongoDB\UpdateResult $result */
         $result = $this->collection->$method(
-            TypeConverter::convertLegacyArrayToObject($criteria),
-            TypeConverter::convertLegacyArrayToObject($newobj),
+            TypeConverter::fromLegacy($criteria),
+            TypeConverter::fromLegacy($newobj),
             $this->convertWriteConcernOptions($options)
         );
 
@@ -359,7 +358,7 @@ class MongoCollection
 
         /** @var \MongoDB\DeleteResult $result */
         $result = $this->collection->$method(
-            TypeConverter::convertLegacyArrayToObject($criteria),
+            TypeConverter::fromLegacy($criteria),
             $this->convertWriteConcernOptions($options)
         );
 
@@ -401,7 +400,7 @@ class MongoCollection
      */
     public function distinct($key, array $query = [])
     {
-        return array_map([TypeConverter::class, 'convertToLegacyType'], $this->collection->distinct($key, $query));
+        return array_map([TypeConverter::class, 'toLegacy'], $this->collection->distinct($key, $query));
     }
 
     /**
@@ -416,26 +415,26 @@ class MongoCollection
      */
     public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
     {
-        $query = TypeConverter::convertLegacyArrayToObject($query);
+        $query = TypeConverter::fromLegacy($query);
 
         if (isset($options['remove'])) {
             unset($options['remove']);
             $document = $this->collection->findOneAndDelete($query, $options);
         } else {
-            $update = is_array($update) ? TypeConverter::convertLegacyArrayToObject($update) : [];
+            $update = is_array($update) ? TypeConverter::fromLegacy($update) : [];
 
             if (isset($options['new'])) {
                 $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
                 unset($options['new']);
             }
 
-            $options['projection'] = is_array($fields) ? TypeConverter::convertLegacyArrayToObject($fields) : [];
+            $options['projection'] = is_array($fields) ? TypeConverter::fromLegacy($fields) : [];
 
             $document = $this->collection->findOneAndUpdate($query, $update, $options);
         }
 
         if ($document) {
-            $document = TypeConverter::convertObjectToLegacyArray($document);
+            $document = TypeConverter::toLegacy($document);
         }
 
         return $document;
@@ -454,9 +453,9 @@ class MongoCollection
     {
         $options = ['projection' => $fields] + $options;
 
-        $document = $this->collection->findOne(TypeConverter::convertLegacyArrayToObject($query), $options);
+        $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options);
         if ($document !== null) {
-            $document = TypeConverter::convertObjectToLegacyArray($document);
+            $document = TypeConverter::toLegacy($document);
         }
 
         return $document;
@@ -518,7 +517,7 @@ class MongoCollection
             throw new \InvalidArgumentException();
         }
 
-        return TypeConverter::convertObjectToLegacyArray($this->collection->dropIndex($indexName));
+        return TypeConverter::toLegacy($this->collection->dropIndex($indexName));
     }
 
     /**
@@ -529,7 +528,7 @@ class MongoCollection
      */
     public function deleteIndexes()
     {
-        return TypeConverter::convertObjectToLegacyArray($this->collection->dropIndexes());
+        return TypeConverter::toLegacy($this->collection->dropIndexes());
     }
 
     /**
@@ -562,7 +561,7 @@ class MongoCollection
      */
     public function count($query = [], array $options = [])
     {
-        return $this->collection->count(TypeConverter::convertLegacyArrayToObject($query), $options);
+        return $this->collection->count(TypeConverter::fromLegacy($query), $options);
     }
 
     /**

+ 8 - 1
lib/Mongo/MongoCommandCursor.php

@@ -53,7 +53,14 @@ class MongoCommandCursor extends AbstractCursor implements MongoCursorInterface
     protected function ensureCursor()
     {
         if ($this->cursor === null) {
-            $this->cursor = $this->db->command(TypeConverter::convertLegacyArrayToObject($this->command), $this->getOptions());
+            $convertedCommand = TypeConverter::fromLegacy($this->command);
+            if (isset($convertedCommand->cursor)) {
+                if ($convertedCommand->cursor === true || $convertedCommand->cursor === []) {
+                    $convertedCommand->cursor = new \stdClass();
+                }
+            }
+
+            $this->cursor = $this->db->command($convertedCommand, $this->getOptions());
         }
 
         return $this->cursor;

+ 2 - 2
lib/Mongo/MongoDB.php

@@ -221,7 +221,7 @@ class MongoDB
      */
     public function drop()
     {
-        return TypeConverter::convertObjectToLegacyArray($this->db->drop());
+        return TypeConverter::toLegacy($this->db->drop());
     }
 
     /**
@@ -279,7 +279,7 @@ class MongoDB
             $coll = $coll->getName();
         }
 
-        return TypeConverter::convertObjectToLegacyArray($this->db->dropCollection((string) $coll));
+        return TypeConverter::toLegacy($this->db->dropCollection((string) $coll));
     }
 
     /**

+ 1 - 1
tests/Alcaeus/MongoDbAdapter/MongoCommandCursorTest.php

@@ -27,7 +27,7 @@ class MongoCommandCursorTest extends TestCase
                         '$match' => ['foo' => 'bar']
                     ]
                 ],
-                'cursor' => new \stdClass()
+                'cursor' => true,
             ],
             'fields' => null,
             'started_iterating' => false,