Skip to content

Commit 65bfb0a

Browse files
author
Michael Chiocca
committed
Fix divisibleBy for small numbers per draft unit tests.
1 parent 38ceb74 commit 65bfb0a

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/JsonSchema/Constraints/Number.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,26 @@ public function check($element, $schema = null, $path = null, $i = null)
5353
}
5454

5555
// Verify divisibleBy
56-
if (isset($schema->divisibleBy) && fmod($element, $schema->divisibleBy) != 0) {
56+
if (isset($schema->divisibleBy) && $this->fmod($element, $schema->divisibleBy) != 0) {
5757
$this->addError($path, "is not divisible by " . $schema->divisibleBy);
5858
}
5959

6060
$this->checkFormat($element, $schema, $path, $i);
6161
}
62-
}
62+
63+
private function fmod($number1, $number2)
64+
{
65+
$modulus = fmod($number1, $number2);
66+
$precision = abs(0.0000000001);
67+
$diff = (float)($modulus - $number2);
68+
69+
if (-$precision < $diff && $diff < $precision) {
70+
return 0.0;
71+
}
72+
73+
$decimals1 = mb_strpos($number1, ".") ? mb_strlen($number1) - mb_strpos($number1, ".") - 1 : 0;
74+
$decimals2 = mb_strpos($number2, ".") ? mb_strlen($number2) - mb_strpos($number2, ".") - 1 : 0;
75+
76+
return (float)round($modulus, max($decimals1, $decimals2));
77+
}
78+
}

tests/JsonSchema/Tests/Constraints/DivisibleByTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,22 @@ public function getValidTests()
7373
"value": {"type": "number", "divisibleBy": 1.5}
7474
}
7575
}'
76+
),
77+
array(
78+
'{"value": 0.0075}',
79+
'{
80+
"properties": {
81+
"value": {"type": "number", "divisibleBy": 0.0001}
82+
}
83+
}'
84+
),
85+
array(
86+
'{"value": 1}',
87+
'{
88+
"properties": {
89+
"value": {"type": "number", "divisibleBy": 0.02}
90+
}
91+
}'
7692
)
7793
);
7894
}

0 commit comments

Comments
 (0)