NumericComparator.php (2686B)
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 11 namespace SebastianBergmann\Comparator; 12 13 /** 14 * Compares numerical values for equality. 15 */ 16 class NumericComparator extends ScalarComparator 17 { 18 /** 19 * Returns whether the comparator can compare two values. 20 * 21 * @param mixed $expected The first value to compare 22 * @param mixed $actual The second value to compare 23 * @return bool 24 */ 25 public function accepts($expected, $actual) 26 { 27 // all numerical values, but not if one of them is a double 28 // or both of them are strings 29 return is_numeric($expected) && is_numeric($actual) && 30 !(is_double($expected) || is_double($actual)) && 31 !(is_string($expected) && is_string($actual)); 32 } 33 34 /** 35 * Asserts that two values are equal. 36 * 37 * @param mixed $expected The first value to compare 38 * @param mixed $actual The second value to compare 39 * @param float $delta The allowed numerical distance between two values to 40 * consider them equal 41 * @param bool $canonicalize If set to TRUE, arrays are sorted before 42 * comparison 43 * @param bool $ignoreCase If set to TRUE, upper- and lowercasing is 44 * ignored when comparing string values 45 * @throws ComparisonFailure Thrown when the comparison 46 * fails. Contains information about the 47 * specific errors that lead to the failure. 48 */ 49 public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false) 50 { 51 if (is_infinite($actual) && is_infinite($expected)) { 52 return; 53 } 54 55 if ((is_infinite($actual) xor is_infinite($expected)) || 56 (is_nan($actual) or is_nan($expected)) || 57 abs($actual - $expected) > $delta) { 58 throw new ComparisonFailure( 59 $expected, 60 $actual, 61 '', 62 '', 63 false, 64 sprintf( 65 'Failed asserting that %s matches expected %s.', 66 $this->exporter->export($actual), 67 $this->exporter->export($expected) 68 ) 69 ); 70 } 71 } 72 }