NumericComparator.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * This file is part of sebastian/comparator.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  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 SebastianBergmann\Comparator;
  11. /**
  12. * Compares numerical values for equality.
  13. */
  14. class NumericComparator extends ScalarComparator
  15. {
  16. /**
  17. * Returns whether the comparator can compare two values.
  18. *
  19. * @param mixed $expected The first value to compare
  20. * @param mixed $actual The second value to compare
  21. *
  22. * @return bool
  23. */
  24. public function accepts($expected, $actual)
  25. {
  26. // all numerical values, but not if both of them are strings
  27. return \is_numeric($expected) && \is_numeric($actual) &&
  28. !(\is_string($expected) && \is_string($actual));
  29. }
  30. /**
  31. * Asserts that two values are equal.
  32. *
  33. * @param mixed $expected First value to compare
  34. * @param mixed $actual Second value to compare
  35. * @param float $delta Allowed numerical distance between two values to consider them equal
  36. * @param bool $canonicalize Arrays are sorted before comparison when set to true
  37. * @param bool $ignoreCase Case is ignored when set to true
  38. *
  39. * @throws ComparisonFailure
  40. */
  41. public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
  42. {
  43. if (\is_infinite($actual) && \is_infinite($expected)) {
  44. return; // @codeCoverageIgnore
  45. }
  46. if ((\is_infinite($actual) xor \is_infinite($expected)) ||
  47. (\is_nan($actual) || \is_nan($expected)) ||
  48. \abs($actual - $expected) > $delta) {
  49. throw new ComparisonFailure(
  50. $expected,
  51. $actual,
  52. '',
  53. '',
  54. false,
  55. \sprintf(
  56. 'Failed asserting that %s matches expected %s.',
  57. $this->exporter->export($actual),
  58. $this->exporter->export($expected)
  59. )
  60. );
  61. }
  62. }
  63. }