NumericComparator.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php declare(strict_types=1);
  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. use function abs;
  12. use function is_float;
  13. use function is_infinite;
  14. use function is_nan;
  15. use function is_numeric;
  16. use function is_string;
  17. use function sprintf;
  18. use SebastianBergmann\Exporter\Exporter;
  19. final class NumericComparator extends ScalarComparator
  20. {
  21. public function accepts(mixed $expected, mixed $actual): bool
  22. {
  23. // all numerical values, but not if both of them are strings
  24. return is_numeric($expected) && is_numeric($actual) &&
  25. !(is_string($expected) && is_string($actual));
  26. }
  27. /**
  28. * @throws ComparisonFailure
  29. */
  30. public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0, bool $canonicalize = false, bool $ignoreCase = false): void
  31. {
  32. if ($this->isInfinite($actual) && $this->isInfinite($expected)) {
  33. return;
  34. }
  35. if (($this->isInfinite($actual) xor $this->isInfinite($expected)) ||
  36. ($this->isNan($actual) || $this->isNan($expected)) ||
  37. abs($actual - $expected) > $delta) {
  38. $exporter = new Exporter;
  39. throw new ComparisonFailure(
  40. $expected,
  41. $actual,
  42. '',
  43. '',
  44. sprintf(
  45. 'Failed asserting that %s matches expected %s.',
  46. $exporter->export($actual),
  47. $exporter->export($expected)
  48. )
  49. );
  50. }
  51. }
  52. private function isInfinite(mixed $value): bool
  53. {
  54. return is_float($value) && is_infinite($value);
  55. }
  56. private function isNan(mixed $value): bool
  57. {
  58. return is_float($value) && is_nan($value);
  59. }
  60. }