MongoDateTest.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 testCreateWithBsonDate()
  38. {
  39. $this->skipTestUnless(in_array(TypeInterface::class, class_implements('MongoDate')));
  40. $bsonDate = new \MongoDB\BSON\UTCDateTime(1234567890123);
  41. $date = new \MongoDate($bsonDate);
  42. $this->assertAttributeSame(1234567890, 'sec', $date);
  43. $this->assertAttributeSame(123000, 'usec', $date);
  44. }
  45. }