Skip to content
This repository has been archived by the owner on Dec 27, 2023. It is now read-only.

Commit

Permalink
Added ext-mongodb support
Browse files Browse the repository at this point in the history
  • Loading branch information
castarco committed Mar 5, 2016
1 parent 10319a1 commit bed08d2
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 3 deletions.
29 changes: 29 additions & 0 deletions src/MongodbAdapter.php
@@ -0,0 +1,29 @@
<?php


namespace Litipk\Jiffy;


/**
* Trait MongodbAdapter: Only to be used inside UniversalTimestamp.
* @package Litipk\Jiffy
*/
trait MongodbAdapter
{
/**
* @param \MongoDB\BSON\UTCDatetime $mongoDate
* @return UniversalTimestamp
*/
public static function fromMongodbUTCDateTime(\MongoDB\BSON\UTCDatetime $mongoDate)
{
return UniversalTimestamp::fromMillisecondsTimestamp((int)$mongoDate->__toString());
}

/**
* @return \MongoDate
*/
public function asMongodbUTCDateTime()
{
return new \MongoDB\BSON\UTCDatetime($this->millis);
}
}
10 changes: 7 additions & 3 deletions src/UniversalTimestamp.php
Expand Up @@ -4,10 +4,14 @@
namespace Litipk\Jiffy;


if (!extension_loaded('mongo')) {
trait TsExtension {};
} else {
if (extension_loaded('mongo') && extension_loaded('mongodb')) {
trait TsExtension { use MongoAdapter; use MongodbAdapter; };
} elseif (extension_loaded('mongo')) {
trait TsExtension { use MongoAdapter; };
} elseif (extension_loaded('mongodb')) {
trait TsExtension { use MongodbAdapter; };
} else {
trait TsExtension {};
}


Expand Down
39 changes: 39 additions & 0 deletions tests/MongodbAdapterTests.php
@@ -0,0 +1,39 @@
<?php


use Litipk\Jiffy\UniversalTimestamp;


class MongodbAdapterTests extends \PHPUnit_Framework_TestCase
{
public function testFromMongoDate()
{
if (!extension_loaded('mongodb')) return;

$uTs_A = UniversalTimestamp::now();
$uTs_B = UniversalTimestamp::fromMongodbUTCDateTime(
new \MongoDB\BSON\UTCDatetime($uTs_A->asMilliseconds()+1)
);
$uTs_C = UniversalTimestamp::fromMillisecondsTimestamp($uTs_A->asMilliseconds()+2);

$this->assertGreaterThanOrEqual(4, 5);

$this->assertGreaterThanOrEqual($uTs_A->asMilliseconds(), $uTs_B->asMilliseconds());
$this->assertGreaterThanOrEqual($uTs_B->asMilliseconds(), $uTs_C->asMilliseconds());
$this->assertGreaterThanOrEqual($uTs_A->asMilliseconds(), $uTs_C->asMilliseconds());
}

public function testAsMongoDate()
{
if (!extension_loaded('mongodb')) return;

$ts1 = UniversalTimestamp::fromMongodbUTCDateTime(
new \MongoDB\BSON\UTCDatetime(UniversalTimestamp::now()->asMilliseconds())
);
$md1 = $ts1->asMongodbUTCDateTime();

$this->assertTrue($md1 instanceof \MongoDB\BSON\UTCDatetime);
$this->assertEquals($ts1->asSeconds(), (int)floor(((int)$md1->__toString())/1000));
$this->assertEquals($ts1->asMilliseconds()%1000, ((int)$md1->__toString())%1000);
}
}

0 comments on commit bed08d2

Please sign in to comment.