DateTimeComparator.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. namespace SebastianBergmann\Comparator;
  11. /**
  12. * Compares DateTimeInterface instances for equality.
  13. */
  14. class DateTimeComparator extends ObjectComparator
  15. {
  16. /**
  17. * Returns whether the comparator can compare two values.
  18. *
  19. * @param mixed $expected The first value to compare
  20. * @param mixed $actual The second value to compare
  21. * @return bool
  22. */
  23. public function accepts($expected, $actual)
  24. {
  25. return ($expected instanceof \DateTime || $expected instanceof \DateTimeInterface) &&
  26. ($actual instanceof \DateTime || $actual instanceof \DateTimeInterface);
  27. }
  28. /**
  29. * Asserts that two values are equal.
  30. *
  31. * @param mixed $expected First value to compare
  32. * @param mixed $actual Second value to compare
  33. * @param float $delta Allowed numerical distance between two values to consider them equal
  34. * @param bool $canonicalize Arrays are sorted before comparison when set to true
  35. * @param bool $ignoreCase Case is ignored when set to true
  36. * @param array $processed List of already processed elements (used to prevent infinite recursion)
  37. *
  38. * @throws ComparisonFailure
  39. */
  40. public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = array())
  41. {
  42. $delta = new \DateInterval(sprintf('PT%sS', abs($delta)));
  43. $expectedLower = clone $expected;
  44. $expectedUpper = clone $expected;
  45. if ($actual < $expectedLower->sub($delta) ||
  46. $actual > $expectedUpper->add($delta)) {
  47. throw new ComparisonFailure(
  48. $expected,
  49. $actual,
  50. $this->dateTimeToString($expected),
  51. $this->dateTimeToString($actual),
  52. false,
  53. 'Failed asserting that two DateTime objects are equal.'
  54. );
  55. }
  56. }
  57. /**
  58. * Returns an ISO 8601 formatted string representation of a datetime or
  59. * 'Invalid DateTimeInterface object' if the provided DateTimeInterface was not properly
  60. * initialized.
  61. *
  62. * @param \DateTimeInterface $datetime
  63. * @return string
  64. */
  65. private function dateTimeToString($datetime)
  66. {
  67. $string = $datetime->format('Y-m-d\TH:i:s.uO');
  68. return $string ? $string : 'Invalid DateTimeInterface object';
  69. }
  70. }