DivisibleByValidator.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  12. /**
  13. * Validates that values are a multiple of the given number.
  14. *
  15. * @author Colin O'Dell <colinodell@gmail.com>
  16. */
  17. class DivisibleByValidator extends AbstractComparisonValidator
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. protected function compareValues($value1, $value2)
  23. {
  24. if (!is_numeric($value1)) {
  25. throw new UnexpectedValueException($value1, 'numeric');
  26. }
  27. if (!is_numeric($value2)) {
  28. throw new UnexpectedValueException($value2, 'numeric');
  29. }
  30. if (!$value2 = abs($value2)) {
  31. return false;
  32. }
  33. if (\is_int($value1 = abs($value1)) && \is_int($value2)) {
  34. return 0 === ($value1 % $value2);
  35. }
  36. if (!$remainder = fmod($value1, $value2)) {
  37. return true;
  38. }
  39. return sprintf('%.12e', $value2) === sprintf('%.12e', $remainder);
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. protected function getErrorCode()
  45. {
  46. return DivisibleBy::NOT_DIVISIBLE_BY;
  47. }
  48. }