NumericComparator.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of the Comparator package.
  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. * @return bool
  22. */
  23. public function accepts($expected, $actual)
  24. {
  25. // all numerical values, but not if one of them is a double
  26. // or both of them are strings
  27. return is_numeric($expected) && is_numeric($actual) &&
  28. !(is_double($expected) || is_double($actual)) &&
  29. !(is_string($expected) && is_string($actual));
  30. }
  31. /**
  32. * Asserts that two values are equal.
  33. *
  34. * @param mixed $expected First value to compare
  35. * @param mixed $actual Second value to compare
  36. * @param float $delta Allowed numerical distance between two values to consider them equal
  37. * @param bool $canonicalize Arrays are sorted before comparison when set to true
  38. * @param bool $ignoreCase Case is ignored when set to true
  39. *
  40. * @throws ComparisonFailure
  41. */
  42. public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
  43. {
  44. if (is_infinite($actual) && is_infinite($expected)) {
  45. return;
  46. }
  47. if ((is_infinite($actual) xor is_infinite($expected)) ||
  48. (is_nan($actual) or is_nan($expected)) ||
  49. abs($actual - $expected) > $delta) {
  50. throw new ComparisonFailure(
  51. $expected,
  52. $actual,
  53. '',
  54. '',
  55. false,
  56. sprintf(
  57. 'Failed asserting that %s matches expected %s.',
  58. $this->exporter->export($actual),
  59. $this->exporter->export($expected)
  60. )
  61. );
  62. }
  63. }
  64. }