MongoDateTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests\Mongo;
  3. use Alcaeus\MongoDbAdapter\Tests\TestCase;
  4. use Alcaeus\MongoDbAdapter\TypeInterface;
  5. /**
  6. * @author alcaeus <alcaeus@alcaeus.org>
  7. */
  8. class MongoDateTest extends TestCase
  9. {
  10. public function testTimeZoneDoesNotAlterReturnedDateTime()
  11. {
  12. $initialTZ = ini_get("date.timezone");
  13. ini_set("date.timezone", "UTC");
  14. // Today at 8h 8m 8s
  15. $timestamp = mktime (8, 8, 8); $date = new \MongoDate($timestamp);
  16. $this->assertSame('08:08:08', $date->toDateTime()->format("H:i:s"));
  17. ini_set("date.timezone", "Europe/Paris");
  18. $this->assertSame('08:08:08', $date->toDateTime()->format("H:i:s"));
  19. ini_set("date.timezone", $initialTZ);
  20. }
  21. public function testCreate()
  22. {
  23. $date = new \MongoDate(1234567890, 123456);
  24. $this->assertAttributeSame(1234567890, 'sec', $date);
  25. $this->assertAttributeSame(123000, 'usec', $date);
  26. $this->assertSame('0.12300000 1234567890', (string) $date);
  27. $dateTime = $date->toDateTime();
  28. $this->assertSame(1234567890, $dateTime->getTimestamp());
  29. $this->assertSame('123000', $dateTime->format('u'));
  30. return $date;
  31. }
  32. /**
  33. * @depends testCreate
  34. */
  35. public function testConvertToBson(\MongoDate $date)
  36. {
  37. $this->skipTestUnless($date instanceof TypeInterface);
  38. $dateTime = $date->toDateTime();
  39. $bsonDate = $date->toBSONType();
  40. $this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $bsonDate);
  41. $this->assertSame('1234567890123', (string) $bsonDate);
  42. $bsonDateTime = $bsonDate->toDateTime();
  43. // Compare timestamps to avoid issues with DateTime
  44. $timestamp = $dateTime->format('U') . '.' . $dateTime->format('U');
  45. $bsonTimestamp = $bsonDateTime->format('U') . '.' . $bsonDateTime->format('U');
  46. $this->assertSame((float) $timestamp, (float) $bsonTimestamp);
  47. }
  48. public function testCreateWithString()
  49. {
  50. $date = new \MongoDate('1234567890', '123456');
  51. $this->assertAttributeSame(1234567890, 'sec', $date);
  52. $this->assertAttributeSame(123000, 'usec', $date);
  53. }
  54. public function testCreateWithBsonDate()
  55. {
  56. $this->skipTestUnless(in_array(TypeInterface::class, class_implements('MongoDate')));
  57. $bsonDate = new \MongoDB\BSON\UTCDateTime(1234567890123);
  58. $date = new \MongoDate($bsonDate);
  59. $this->assertAttributeSame(1234567890, 'sec', $date);
  60. $this->assertAttributeSame(123000, 'usec', $date);
  61. }
  62. }