File tree Expand file tree Collapse file tree 3 files changed +41
-9
lines changed
Expand file tree Collapse file tree 3 files changed +41
-9
lines changed Original file line number Diff line number Diff line change 22 "name" : " lewiscowles/ulid" ,
33 "description" : " Universally Unique Lexicographically Sortable Identifier ported to PHP" ,
44 "type" : " library" ,
5+ "require" : {
6+ "php" : " >=7.0"
7+ }
58 "require-dev" : {
9+ "ext-xdebug" : " *" ,
610 "phpunit/phpunit" : " ^5.4"
711 },
812 "license" : " AGPL" ,
Original file line number Diff line number Diff line change 55final class Ulid {
66 const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ " ;
77 const ENCODING_LENGTH = 32 ;
8+ protected $ random_float_src ;
9+
10+ public function __construct (RandomFloatInterface $ rf ){
11+ $ this ->random_float_src = $ rf ;
12+ }
813
914 public function get ()
1015 {
11- return $ this ->encodeTime ($ this ->getTime (), 10 ) . $ this ->encodeRandom (16 );
16+ return sprintf (
17+ "%s%s " ,
18+ $ this ->encodeTime ($ this ->getTime (), 10 ),
19+ $ this ->encodeRandom (16 )
20+ );
1221 }
1322
1423 private function encodeTime (int $ time , int $ length ) : string
@@ -28,20 +37,34 @@ private function encodeRandom(int $length) : string
2837 {
2938 $ out = '' ;
3039 while ($ length > 0 ) {
31- $ rand = intval (floor (self ::ENCODING_LENGTH * $ this ->getRand ()));
40+ $ rand = intval (
41+ floor (
42+ self ::ENCODING_LENGTH
43+ *
44+ $ this ->random_float_src ->generate ()
45+ )
46+ );
3247 $ out = self ::ENCODING [$ rand ] . $ out ;
3348 $ length --;
3449 }
3550 return $ out ;
3651 }
3752
38- private function getRand () : float
39- {
40- return lcg_value ();
41- }
42-
4353 private function getTime () : int
4454 {
4555 return time ();
4656 }
4757}
58+
59+ interface RandomFloatInterface {
60+ public function generate () : float ;
61+ }
62+
63+ class LcgRandomGenerator implements RandomFloatInterface {
64+
65+ public function __construct () { }
66+
67+ public function generate () : float {
68+ return lcg_value ();
69+ }
70+ }
Original file line number Diff line number Diff line change 44require_once __DIR__ .'/../src/ulid.php ' ;
55
66use lewiscowles \core \Ulid ;
7+ use lewiscowles \core \LcgRandomGenerator ;
78
89use PHPUnit \Framework \TestCase ;
910
@@ -14,12 +15,16 @@ class BaseTest extends TestCase
1415
1516 public function setup ()
1617 {
17- $ this ->ulid = new Ulid ();
18+ $ this ->ulid = new Ulid ($ this ->getLcgRandom ());
19+ }
20+
21+ public function getLcgRandom () {
22+ return new LcgRandomGenerator ();
1823 }
1924
2025 public function testRandIsBetween1and0 ()
2126 {
22- $ rand = $ this ->invokeMethod ( $ this -> ulid , ' getRand ' );
27+ $ rand = $ this ->getLcgRandom ()-> generate ( );
2328 $ this ->assertTrue ( $ rand > 0 && $ rand < 1 );
2429 }
2530
You can’t perform that action at this time.
0 commit comments