-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[Validator] Improve DivisibleBy validator #28212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,7 +23,26 @@ class DivisibleByValidator extends AbstractComparisonValidator | |
*/ | ||
protected function compareValues($value1, $value2) | ||
{ | ||
return (float) 0 === fmod($value1, $value2); | ||
$value1 = \abs($value1); | ||
$value2 = \abs($value2); | ||
$epsilon = 0.0000001; | ||
|
||
// can't divide by 0 | ||
if ($value2 < $epsilon) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't this trigger an exception when the constraint is configured with such an invalid value? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure. The previous implementation with fmod just returned NaN (so the validator failed). We can change it, I just adapted the previous behavior. |
||
return false; | ||
} | ||
|
||
// 0 is divisible by everything | ||
if ($value1 < $epsilon) { | ||
return true; | ||
} | ||
|
||
// if the divisor is larger than the dividend, it will never cleanly divide | ||
if ($value2 > $value1) { | ||
return false; | ||
} | ||
|
||
return \abs($value1 - round($value1 / $value2) * $value2) < $epsilon; | ||
} | ||
|
||
/** | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What about making this configurable?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I‘m not sure whether this would actually add anything.
Might make sense to add something like FloatUtils to capsiluate some of this logic (comparing floats etc)