Skip to content
This repository has been archived by the owner on May 12, 2018. It is now read-only.

Commit

Permalink
Improve type: number validation (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt A committed Nov 18, 2016
1 parent 1ff119c commit 7863d0b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/Constraints/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,13 @@ public static function validate($value, $type, $pointer = null)
case 'null':
return self::validateType($value, $type, 'is_null', ErrorCode::INVALID_NULL, $pointer);
case 'number':
return self::validateType($value, $type, 'is_numeric', ErrorCode::INVALID_NUMERIC, $pointer);
return self::validateType(
$value,
$type,
'League\JsonGuard\is_json_number',
ErrorCode::INVALID_NUMERIC,
$pointer
);
case 'integer':
return self::validateType(
$value,
Expand Down
15 changes: 14 additions & 1 deletion src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ function escape_pointer($pointer)
* Determines if the value is an integer or an integer that was cast to a string
* because it is larger than PHP_INT_MAX.
*
* @param mixed $value
* @param mixed $value
* @return boolean
*/
function is_json_integer($value)
Expand All @@ -143,6 +143,19 @@ function is_json_integer($value)
return is_int($value) || (is_string($value) && ctype_digit($value) && compare($value, PHP_INT_MAX) === 1);
}

/**
* Determines if the value is a number. A number is a float, integer, or a number that was cast
* to a string because it is larger than PHP_INT_MAX.
*
* @param mixed $value
*
* @return boolean
*/
function is_json_number($value)
{
return is_float($value) || is_json_integer($value);
}

/**
* @param string|double|int $leftOperand
* @param string|double|int $rightOperand
Expand Down
18 changes: 18 additions & 0 deletions tests/Constraints/TypeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace League\JsonGuard\Test\Constraints;

use League\JsonGuard\Constraints\Type;
use League\JsonGuard\ValidationError;

class TypeTest extends \PHPUnit_Framework_TestCase
{
public function testNumericStringIsNotANumber()
{
$type = new Type();

$error = $type->validate('1', 'number');

$this->assertInstanceOf(ValidationError::class, $error);
}
}

0 comments on commit 7863d0b

Please sign in to comment.