ScalarComparator.php (3646B)
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 scalar or NULL values for equality. 15 */ 16 class ScalarComparator extends Comparator 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 * @since Method available since Release 3.6.0 25 */ 26 public function accepts($expected, $actual) 27 { 28 return ((is_scalar($expected) xor null === $expected) && 29 (is_scalar($actual) xor null === $actual)) 30 // allow comparison between strings and objects featuring __toString() 31 || (is_string($expected) && is_object($actual) && method_exists($actual, '__toString')) 32 || (is_object($expected) && method_exists($expected, '__toString') && is_string($actual)); 33 } 34 35 /** 36 * Asserts that two values are equal. 37 * 38 * @param mixed $expected The first value to compare 39 * @param mixed $actual The second value to compare 40 * @param float $delta The allowed numerical distance between two values to 41 * consider them equal 42 * @param bool $canonicalize If set to TRUE, arrays are sorted before 43 * comparison 44 * @param bool $ignoreCase If set to TRUE, upper- and lowercasing is 45 * ignored when comparing string values 46 * @throws ComparisonFailure Thrown when the comparison 47 * fails. Contains information about the 48 * specific errors that lead to the failure. 49 */ 50 public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false) 51 { 52 $expectedToCompare = $expected; 53 $actualToCompare = $actual; 54 55 // always compare as strings to avoid strange behaviour 56 // otherwise 0 == 'Foobar' 57 if (is_string($expected) || is_string($actual)) { 58 $expectedToCompare = (string) $expectedToCompare; 59 $actualToCompare = (string) $actualToCompare; 60 61 if ($ignoreCase) { 62 $expectedToCompare = strtolower($expectedToCompare); 63 $actualToCompare = strtolower($actualToCompare); 64 } 65 } 66 67 if ($expectedToCompare != $actualToCompare) { 68 if (is_string($expected) && is_string($actual)) { 69 throw new ComparisonFailure( 70 $expected, 71 $actual, 72 $this->exporter->export($expected), 73 $this->exporter->export($actual), 74 false, 75 'Failed asserting that two strings are equal.' 76 ); 77 } 78 79 throw new ComparisonFailure( 80 $expected, 81 $actual, 82 // no diff is required 83 '', 84 '', 85 false, 86 sprintf( 87 'Failed asserting that %s matches expected %s.', 88 $this->exporter->export($actual), 89 $this->exporter->export($expected) 90 ) 91 ); 92 } 93 } 94 }