Skip to content

Commit

Permalink
Merge pull request #6 from Lewiscowles1986/injectable-time
Browse files Browse the repository at this point in the history
Added injectable time-source
  • Loading branch information
Lewiscowles1986 authored Dec 9, 2016
2 parents 87b8597 + 91dc838 commit 2d8fc25
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
24 changes: 17 additions & 7 deletions src/ulid.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@
final class Ulid {
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const ENCODING_LENGTH = 32;
protected $time_src;
protected $random_float_src;

public function __construct(RandomFloatInterface $rf){
public function __construct(TimeSourceInterface $ts, RandomFloatInterface $rf) {
$this->time_src = $ts;
$this->random_float_src = $rf;
}

public function get()
{
return sprintf(
"%s%s",
$this->encodeTime($this->getTime(), 10),
$this->encodeTime($this->time_src->getTime(), 10),
$this->encodeRandom(16)
);
}
Expand Down Expand Up @@ -49,11 +51,6 @@ private function encodeRandom(int $length) : string
}
return $out;
}

private function getTime() : int
{
return time();
}
}

interface RandomFloatInterface {
Expand All @@ -68,3 +65,16 @@ public function generate() : float {
return lcg_value();
}
}

interface TimeSourceInterface {
public function getTime() : int;
}

class PHPTimeSource implements TimeSourceInterface {

public function __construct() { }

public function getTime() : int {
return time();
}
}
8 changes: 6 additions & 2 deletions tests/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

use lewiscowles\core\Ulid;
use lewiscowles\core\LcgRandomGenerator;

use lewiscowles\core\PHPTimeSource;
use PHPUnit\Framework\TestCase;

class BaseTest extends TestCase
Expand All @@ -15,7 +15,11 @@ class BaseTest extends TestCase

public function setup()
{
$this->ulid = new Ulid($this->getLcgRandom());
$this->ulid = new Ulid($this->getTimeSource(), $this->getLcgRandom());
}

public function getTimeSource() {
return new PHPTimeSource();
}

public function getLcgRandom() {
Expand Down

0 comments on commit 2d8fc25

Please sign in to comment.