Permalink
Browse files

InvalidArgumentException::assertNumeric()

  • Loading branch information...
1 parent bd1f04f commit f1f2f8f5fc8b279d35e17d6313aec3bf1a7ea457 @lstrojny committed Nov 1, 2011
@@ -135,13 +135,12 @@ public static function assertPositiveInteger($value, $callee, $parameterPosition
public static function assertValidArrayKey($key, $callee)
{
$keyTypes = array('NULL', 'string', 'integer', 'double', 'boolean');
-
$keyType = gettype($key);
if (!in_array($keyType, $keyTypes, true)) {
throw new static(
sprintf(
- '%s(): callback returned invalid array key of type "%s". Expected %4$s or %3$s',
+ '%1$s(): callback returned invalid array key of type "%2$s". Expected %4$s or %3$s',
$callee,
$keyType,
array_pop($keyTypes),
@@ -150,4 +149,18 @@ public static function assertValidArrayKey($key, $callee)
);
}
}
+
+ public static function assertNumeric($value, $callee, $parmeterPosition)
+ {
+ if (!is_numeric($value)) {
+ throw new static(
+ sprintf(
+ '%s() expects parameter %d to be numeric (integer, float or numeric string), %s given',
+ $callee,
+ $parmeterPosition,
+ gettype($value)
+ )
+ );
+ }
+ }
}
@@ -135,4 +135,34 @@ function testExceptionIfStringInsteadOfPositiveInteger()
);
InvalidArgumentException::assertPositiveInteger('str', 'func', 2);
}
+
+ function testExceptionIfStringInsteadOfNumber()
+ {
+ $this->setExpectedException(
+ 'Functional\Exceptions\InvalidArgumentException',
+ 'func() expects parameter 2 to be numeric (integer, float or numeric string), string given'
+ );
+ InvalidArgumentException::assertNumeric('str', 'func', 2);
+ }
+
+ function testExceptionIfObjectInsteadOfNumber()
+ {
+ $this->setExpectedException(
+ 'Functional\Exceptions\InvalidArgumentException',
+ 'func() expects parameter 2 to be numeric (integer, float or numeric string), object given'
+ );
+ InvalidArgumentException::assertNumeric((object)array(), 'func', 2);
+ }
+
+ function testIntegerFloatsAndNumericStringsAreOkWithAssertNumeric()
+ {
+ $this->assertNull(InvalidArgumentException::assertNumeric(1, 'str', 1));
+ $this->assertNull(InvalidArgumentException::assertNumeric(-1, 'str', 1));
+ $this->assertNull(InvalidArgumentException::assertNumeric(1.0, 'str', 1));
+ $this->assertNull(InvalidArgumentException::assertNumeric(-1.0, 'str', 1));
+ $this->assertNull(InvalidArgumentException::assertNumeric("1", 'str', 1));
+ $this->assertNull(InvalidArgumentException::assertNumeric("-1", 'str', 1));
+ $this->assertNull(InvalidArgumentException::assertNumeric("1.0", 'str', 1));
+ $this->assertNull(InvalidArgumentException::assertNumeric("-1.0", 'str', 1));
+ }
}

0 comments on commit f1f2f8f

Please sign in to comment.