Browse Source

Don't forcibly cast all data.

Casting everything to int/float has some advantages like always having
the correct types, but it also has drawbacks - makes validation hard.

This change takes a middle ground approach where data is cast if has the
correct approximate type. While these checks are far from perfect they
avoid casting totally invalid data.

Refs #4790
Mark Story 11 years ago
parent
commit
bc4bd070d4

+ 4 - 1
src/Database/Type/FloatType.php

@@ -74,7 +74,10 @@ class FloatType extends \Cake\Database\Type {
 		if ($value === null || $value === '') {
 			return null;
 		}
-		return floatval($value);
+		if (is_numeric($value)) {
+			return (float)$value;
+		}
+		return $value;
 	}
 
 }

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

@@ -74,7 +74,13 @@ class IntegerType extends \Cake\Database\Type {
 		if ($value === null || $value === '') {
 			return null;
 		}
-		return (int)$value;
+		if (is_int($value)) {
+			return $value;
+		}
+		if (ctype_digit($value)) {
+			return (int)$value;
+		}
+		return $value;
 	}
 
 }

+ 4 - 1
tests/TestCase/Database/Type/FloatTypeTest.php

@@ -76,13 +76,16 @@ class FloatTypeTest extends TestCase {
  */
 	public function testMarshal() {
 		$result = $this->type->marshal('some data', $this->driver);
-		$this->assertSame(0.0, $result);
+		$this->assertSame('some data', $result);
 
 		$result = $this->type->marshal('', $this->driver);
 		$this->assertNull($result);
 
 		$result = $this->type->marshal('2.51', $this->driver);
 		$this->assertSame(2.51, $result);
+
+		$result = $this->type->marshal('3.5 bears', $this->driver);
+		$this->assertSame('3.5 bears', $result);
 	}
 
 /**

+ 13 - 1
tests/TestCase/Database/Type/IntegerTypeTest.php

@@ -76,13 +76,25 @@ class IntegerTypeTest extends TestCase {
  */
 	public function testMarshal() {
 		$result = $this->type->marshal('some data', $this->driver);
-		$this->assertSame(0, $result);
+		$this->assertSame('some data', $result);
 
 		$result = $this->type->marshal('', $this->driver);
 		$this->assertNull($result);
 
 		$result = $this->type->marshal('0', $this->driver);
 		$this->assertSame(0, $result);
+
+		$result = $this->type->marshal('105', $this->driver);
+		$this->assertSame(105, $result);
+
+		$result = $this->type->marshal(105, $this->driver);
+		$this->assertSame(105, $result);
+
+		$result = $this->type->marshal('1.25', $this->driver);
+		$this->assertSame('1.25', $result);
+
+		$result = $this->type->marshal('2 monkeys', $this->driver);
+		$this->assertSame('2 monkeys', $result);
 	}
 
 /**