Forráskód Böngészése

Harden detection for numeric arrays

Andreas Braun 9 éve
szülő
commit
c1182019bc

+ 8 - 1
lib/Alcaeus/MongoDbAdapter/TypeConverter.php

@@ -138,7 +138,14 @@ class TypeConverter
      */
     public static function isNumericArray(array $array)
     {
-        return $array === [] || is_numeric(array_keys($array)[0]);
+        if ($array === []) {
+            return true;
+        }
+
+        $keys = array_keys($array);
+        // array_keys gives us a clean numeric array with keys, so we expect an
+        // array like [0 => 0, 1 => 1, 2 => 2, ..., n => n]
+        return array_values($keys) === array_keys($keys);
     }
 
     /**

+ 19 - 0
tests/Alcaeus/MongoDbAdapter/TypeConverterTest.php

@@ -40,4 +40,23 @@ class TypeConverterTest extends TestCase
             ],
         ];
     }
+
+    /**
+     * @dataProvider dataIsNumericArray
+     */
+    public function testIsNumericArray($expected, $array)
+    {
+        $this->assertSame($expected, TypeConverter::isNumericArray($array));
+    }
+
+    public static function dataIsNumericArray()
+    {
+        return [
+            'emptyArray' => [true, []],
+            'arrayWithSequentialIndices' => [true, [1, 2, 3]],
+            'arrayWithSequentialIndicesOneBased' => [false, [1 => 1, 2, 3]],
+            'arrayWithStringKeys' => [false, ['foo' => 'bar']],
+            'arrayWithRandomNumbers' => [false, [15 => 'foo', 20 => 'bar']],
+        ];
+    }
 }