3 * This file is part of the Comparator package.
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace SebastianBergmann\Comparator;
14 * Compares DateTimeInterface instances for equality.
16 class DateTimeComparator extends ObjectComparator
19 * Returns whether the comparator can compare two values.
21 * @param mixed $expected The first value to compare
22 * @param mixed $actual The second value to compare
25 public function accepts($expected, $actual)
27 return ($expected instanceof \DateTime || $expected instanceof \DateTimeInterface) &&
28 ($actual instanceof \DateTime || $actual instanceof \DateTimeInterface);
32 * Asserts that two values are equal.
34 * @param mixed $expected First value to compare
35 * @param mixed $actual Second value to compare
36 * @param float $delta Allowed numerical distance between two values to consider them equal
37 * @param bool $canonicalize Arrays are sorted before comparison when set to true
38 * @param bool $ignoreCase Case is ignored when set to true
39 * @param array $processed List of already processed elements (used to prevent infinite recursion)
41 * @throws ComparisonFailure
43 public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = array())
45 $delta = new \DateInterval(sprintf('PT%sS', abs($delta)));
47 $expectedLower = clone $expected;
48 $expectedUpper = clone $expected;
50 if ($actual < $expectedLower->sub($delta) ||
51 $actual > $expectedUpper->add($delta)) {
52 throw new ComparisonFailure(
55 $this->dateTimeToString($expected),
56 $this->dateTimeToString($actual),
58 'Failed asserting that two DateTime objects are equal.'
64 * Returns an ISO 8601 formatted string representation of a datetime or
65 * 'Invalid DateTimeInterface object' if the provided DateTimeInterface was not properly
68 * @param \DateTimeInterface $datetime
71 private function dateTimeToString($datetime)
73 $string = $datetime->format('Y-m-d\TH:i:s.uO');
75 return $string ? $string : 'Invalid DateTimeInterface object';