Browse Source

Throw exception on `manyToPHP()` for non-numeric.

Dustin Haggard 7 years ago
parent
commit
c642ca7bd9

+ 9 - 1
src/Database/Type/IntegerType.php

@@ -98,9 +98,17 @@ class IntegerType extends Type implements TypeInterface, BatchCastingInterface
     public function manyToPHP(array $values, array $fields, Driver $driver)
     {
         foreach ($fields as $field) {
-            if (!isset($values[$field]) || !is_numeric($values[$field])) {
+            if (!isset($values[$field])) {
                 continue;
             }
+
+            if ($values[$field] !== null && $values[$field] !== '' && !is_numeric($values[$field])) {
+                throw new InvalidArgumentException(sprintf(
+                    'Cannot convert value of type `%s` to integer',
+                    getTypeName($values[$field])
+                ));
+            }
+
             $values[$field] = (int)$values[$field];
         }
 

+ 28 - 0
tests/TestCase/Database/Type/IntegerTypeTest.php

@@ -79,6 +79,34 @@ class IntegerTypeTest extends TestCase
             'b' => '2.3',
             'c' => '15',
             'd' => '0.0',
+            'e' => 10
+        ];
+        $expected = [
+            'a' => null,
+            'b' => 2,
+            'c' => 15,
+            'd' => 0,
+            'e' => 10
+        ];
+        $this->assertEquals(
+            $expected,
+            $this->type->manyToPHP($values, array_keys($values), $this->driver)
+        );
+    }
+
+    /**
+     * Test to make sure the method throws an exception for invalid integer values.
+     *
+     * @return void
+     */
+    public function testInvalidManyToPHP()
+    {
+        $this->expectException(\InvalidArgumentException::class);
+        $values = [
+            'a' => null,
+            'b' => '2.3',
+            'c' => '15',
+            'd' => '0.0',
             'e' => 10,
             'f' => '6a88accf-a34e-4dd9-ade0-8d255ccaecbe'
         ];