Skip to content

Commit 2d8fc25

Browse files
Merge pull request #6 from Lewiscowles1986/injectable-time
Added injectable time-source
2 parents 87b8597 + 91dc838 commit 2d8fc25

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed

src/ulid.php

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,19 @@
55
final class Ulid {
66
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
77
const ENCODING_LENGTH = 32;
8+
protected $time_src;
89
protected $random_float_src;
910

10-
public function __construct(RandomFloatInterface $rf){
11+
public function __construct(TimeSourceInterface $ts, RandomFloatInterface $rf) {
12+
$this->time_src = $ts;
1113
$this->random_float_src = $rf;
1214
}
1315

1416
public function get()
1517
{
1618
return sprintf(
1719
"%s%s",
18-
$this->encodeTime($this->getTime(), 10),
20+
$this->encodeTime($this->time_src->getTime(), 10),
1921
$this->encodeRandom(16)
2022
);
2123
}
@@ -49,11 +51,6 @@ private function encodeRandom(int $length) : string
4951
}
5052
return $out;
5153
}
52-
53-
private function getTime() : int
54-
{
55-
return time();
56-
}
5754
}
5855

5956
interface RandomFloatInterface {
@@ -68,3 +65,16 @@ public function generate() : float {
6865
return lcg_value();
6966
}
7067
}
68+
69+
interface TimeSourceInterface {
70+
public function getTime() : int;
71+
}
72+
73+
class PHPTimeSource implements TimeSourceInterface {
74+
75+
public function __construct() { }
76+
77+
public function getTime() : int {
78+
return time();
79+
}
80+
}

tests/BaseTest.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
use lewiscowles\core\Ulid;
77
use lewiscowles\core\LcgRandomGenerator;
8-
8+
use lewiscowles\core\PHPTimeSource;
99
use PHPUnit\Framework\TestCase;
1010

1111
class BaseTest extends TestCase
@@ -15,7 +15,11 @@ class BaseTest extends TestCase
1515

1616
public function setup()
1717
{
18-
$this->ulid = new Ulid($this->getLcgRandom());
18+
$this->ulid = new Ulid($this->getTimeSource(), $this->getLcgRandom());
19+
}
20+
21+
public function getTimeSource() {
22+
return new PHPTimeSource();
1923
}
2024

2125
public function getLcgRandom() {

0 commit comments

Comments
 (0)