MongoDateTest.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 testCreate()
  11. {
  12. $date = new \MongoDate(1234567890, 123456);
  13. $this->assertAttributeSame(1234567890, 'sec', $date);
  14. $this->assertAttributeSame(123000, 'usec', $date);
  15. $this->assertSame('0.12300000 1234567890', (string) $date);
  16. $dateTime = $date->toDateTime();
  17. $this->assertSame(1234567890, $dateTime->getTimestamp());
  18. $this->assertSame('123000', $dateTime->format('u'));
  19. return $date;
  20. }
  21. /**
  22. * @depends testCreate
  23. */
  24. public function testConvertToBson(\MongoDate $date)
  25. {
  26. $this->skipTestUnless($date instanceof TypeInterface);
  27. $dateTime = $date->toDateTime();
  28. $bsonDate = $date->toBSONType();
  29. $this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $bsonDate);
  30. $this->assertSame('1234567890123', (string) $bsonDate);
  31. $bsonDateTime = $bsonDate->toDateTime();
  32. // Compare timestamps to avoid issues with DateTime
  33. $timestamp = $dateTime->format('U') . '.' . $dateTime->format('U');
  34. $bsonTimestamp = $bsonDateTime->format('U') . '.' . $bsonDateTime->format('U');
  35. $this->assertSame((float) $timestamp, (float) $bsonTimestamp);
  36. }
  37. public function testCreateWithString()
  38. {
  39. $date = new \MongoDate('1234567890', '123456');
  40. $this->assertAttributeSame(1234567890, 'sec', $date);
  41. $this->assertAttributeSame(123000, 'usec', $date);
  42. }
  43. public function testCreateWithBsonDate()
  44. {
  45. $this->skipTestUnless(in_array(TypeInterface::class, class_implements('MongoDate')));
  46. $bsonDate = new \MongoDB\BSON\UTCDateTime(1234567890123);
  47. $date = new \MongoDate($bsonDate);
  48. $this->assertAttributeSame(1234567890, 'sec', $date);
  49. $this->assertAttributeSame(123000, 'usec', $date);
  50. }
  51. }