DateTimeComparator.php (2963B)
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 DateTimeInterface instances for equality. 15 */ 16 class DateTimeComparator extends ObjectComparator 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 return ($expected instanceof \DateTime || $expected instanceof \DateTimeInterface) && 28 ($actual instanceof \DateTime || $actual instanceof \DateTimeInterface); 29 } 30 31 /** 32 * Asserts that two values are equal. 33 * 34 * @param mixed $expected The first value to compare 35 * @param mixed $actual The second value to compare 36 * @param float $delta The allowed numerical distance between two values to 37 * consider them equal 38 * @param bool $canonicalize If set to TRUE, arrays are sorted before 39 * comparison 40 * @param bool $ignoreCase If set to TRUE, upper- and lowercasing is 41 * ignored when comparing string values 42 * @throws ComparisonFailure Thrown when the comparison 43 * fails. Contains information about the 44 * specific errors that lead to the failure. 45 */ 46 public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false) 47 { 48 $delta = new \DateInterval(sprintf('PT%sS', abs($delta))); 49 50 $expectedLower = clone $expected; 51 $expectedUpper = clone $expected; 52 53 if ($actual < $expectedLower->sub($delta) || 54 $actual > $expectedUpper->add($delta)) { 55 throw new ComparisonFailure( 56 $expected, 57 $actual, 58 $this->dateTimeToString($expected), 59 $this->dateTimeToString($actual), 60 false, 61 'Failed asserting that two DateTime objects are equal.' 62 ); 63 } 64 } 65 66 /** 67 * Returns an ISO 8601 formatted string representation of a datetime or 68 * 'Invalid DateTimeInterface object' if the provided DateTimeInterface was not properly 69 * initialized. 70 * 71 * @param \DateTimeInterface $datetime 72 * @return string 73 */ 74 protected function dateTimeToString($datetime) 75 { 76 $string = $datetime->format(\DateTime::ISO8601); 77 78 return $string ? $string : 'Invalid DateTimeInterface object'; 79 } 80 }