File: NumberComparator.php

package info (click to toggle)
phpunit-comparator 8.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 33,628 kB
  • sloc: php: 13,147; xml: 62; makefile: 17
file content (66 lines) | stat: -rw-r--r-- 2,264 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php declare(strict_types=1);
/*
 * This file is part of sebastian/comparator.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace SebastianBergmann\Comparator;

use function assert;
use function is_int;
use function is_numeric;
use function is_string;
use function max;
use function number_format;
use BcMath\Number;

/**
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise for sebastian/comparator
 *
 * @internal This class is not covered by the backward compatibility promise for sebastian/comparator
 */
final class NumberComparator extends ObjectComparator
{
    public function accepts(mixed $expected, mixed $actual): bool
    {
        return ($expected instanceof Number || $actual instanceof Number) &&
            ($expected instanceof Number || is_int($expected) || is_string($expected) && is_numeric($expected)) &&
            ($actual instanceof Number || is_int($actual) || is_string($actual) && is_numeric($actual));
    }

    /**
     * @param array<mixed> $processed
     *
     * @throws ComparisonFailure
     */
    public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0, bool $canonicalize = false, bool $ignoreCase = false, array &$processed = []): void
    {
        if (!$expected instanceof Number) {
            assert(is_int($expected) || is_string($expected) && is_numeric($expected));

            $expected = new Number($expected);
        }

        if (!$actual instanceof Number) {
            assert(is_int($actual) || is_string($actual) && is_numeric($actual));

            $actual = new Number($actual);
        }

        /** @phpstan-ignore argument.type */
        $deltaNumber = new Number(number_format($delta, max($expected->scale, $actual->scale)));

        if ($actual < $expected - $deltaNumber || $actual > $expected + $deltaNumber) {
            throw new ComparisonFailure(
                $expected,
                $actual,
                (string) $expected,
                (string) $actual,
                'Failed asserting that two Number objects are equal.',
            );
        }
    }
}