Skip to content

Commit

Permalink
Merge pull request #5 from Lewiscowles1986/random-interface
Browse files Browse the repository at this point in the history
Added Injectable Random Source
  • Loading branch information
Lewiscowles1986 authored Dec 9, 2016
2 parents e9f1011 + 0898db8 commit a1c35d4
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 9 deletions.
4 changes: 4 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
"name": "lewiscowles/ulid",
"description": "Universally Unique Lexicographically Sortable Identifier ported to PHP",
"type": "library",
"require": {
"php": ">=7.0"
}
"require-dev": {
"ext-xdebug": "*",
"phpunit/phpunit": "^5.4"
},
"license": "AGPL",
Expand Down
37 changes: 30 additions & 7 deletions src/ulid.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,19 @@
final class Ulid {
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const ENCODING_LENGTH = 32;
protected $random_float_src;

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

public function get()
{
return $this->encodeTime($this->getTime(), 10) . $this->encodeRandom(16);
return sprintf(
"%s%s",
$this->encodeTime($this->getTime(), 10),
$this->encodeRandom(16)
);
}

private function encodeTime(int $time, int $length) : string
Expand All @@ -28,20 +37,34 @@ private function encodeRandom(int $length) : string
{
$out = '';
while($length > 0) {
$rand = intval(floor(self::ENCODING_LENGTH * $this->getRand()));
$rand = intval(
floor(
self::ENCODING_LENGTH
*
$this->random_float_src->generate()
)
);
$out = self::ENCODING[$rand] . $out;
$length--;
}
return $out;
}

private function getRand() : float
{
return lcg_value();
}

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

interface RandomFloatInterface {
public function generate() : float;
}

class LcgRandomGenerator implements RandomFloatInterface {

public function __construct() { }

public function generate() : float {
return lcg_value();
}
}
9 changes: 7 additions & 2 deletions tests/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
require_once __DIR__.'/../src/ulid.php';

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

use PHPUnit\Framework\TestCase;

Expand All @@ -14,12 +15,16 @@ class BaseTest extends TestCase

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

public function getLcgRandom() {
return new LcgRandomGenerator();
}

public function testRandIsBetween1and0()
{
$rand = $this->invokeMethod($this->ulid, 'getRand');
$rand = $this->getLcgRandom()->generate();
$this->assertTrue( $rand > 0 && $rand < 1 );
}

Expand Down

0 comments on commit a1c35d4

Please sign in to comment.