DateTimeComparator.php 2.9 KB

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