diff --git a/src/BaseId.php b/src/BaseId.php new file mode 100644 index 0000000..bbfc87f --- /dev/null +++ b/src/BaseId.php @@ -0,0 +1,11 @@ +prefix = $prefix; + } + + public function create(...$ids) + { + $this->id = ''; + foreach($ids as $i) { + $this->id .= $this->encode($i); + } + return $this->id; + } + + public function get($length) + { + return $this->prefix . substr($this->id, 0, $length); + } + + public function setPrefix(string $prefix) + { + $this->prefix = $prefix; + } +} diff --git a/src/ObjectId.php b/src/ObjectId.php index e49a9c2..d32c217 100644 --- a/src/ObjectId.php +++ b/src/ObjectId.php @@ -1,51 +1,47 @@ prefix = $prefix; - } +use Bulldog\id\Contracts\ObjectIdInterface; - public function get($length) - { - $parts = []; +class ObjectId extends BaseId implements ObjectIdInterface +{ + protected $prefix; - // By using floor and ceil, if we divide an odd number by 2 - // we only get whole numbers that add up to the length. - $parts[0] = $this->bucket(floor($length / 2)); - $parts[1] = $this->random(ceil($length / 2)); + public function __construct(string $prefix = '') + { + $this->prefix = $prefix; + } - $id = $parts[0].$parts[1]; + public function get($length) + { + $parts = []; - return $this->prefix . $id; - } + // By using floor and ceil, if we divide an odd number by 2 + // we only get whole numbers that add up to the length. + $parts[0] = $this->bucket(floor($length / 2)); + $parts[1] = $this->random(ceil($length / 2)); - public function setPrefix(string $prefix) - { - $this->prefix = $prefix; - } + $id = $parts[0].$parts[1]; - protected function bucket($length) - { - $seconds = time() - mktime(0, 0, 0, 1, 1, date('Y')); - $secondsEncoded = $this->encode($seconds); + return $this->prefix . $id; + } - return substr($secondsEncoded, 0, $length); - } + public function setPrefix(string $prefix) + { + $this->prefix = $prefix; + } + + protected function bucket($length) + { + $seconds = time() - mktime(0, 0, 0, 1, 1, date('Y')); + $secondsEncoded = $this->encode($seconds); - protected function random($length) - { - return substr($this->encode(random_bytes($length)), 0, $length); - } + return substr($secondsEncoded, 0, $length); + } - protected function encode($input) - { - return rtrim(strtr(base64_encode($input), '+/', '-_'), '='); - } + protected function random($length) + { + return substr($this->encode(random_bytes($length)), 0, $length); } } diff --git a/tests/IdTests.php b/tests/IdTests.php index 660d08b..b736504 100644 --- a/tests/IdTests.php +++ b/tests/IdTests.php @@ -75,4 +75,13 @@ public function testUsingSetPrefixMethod() $this->assertFalse($result); } } + + public function testIncrementalId() + { + $iId = new \Bulldog\id\IncrementalId; + + $id = $iId->create(4, 'dog', 9); + $this->assertEquals('NAZG9nOQ', $id); + $this->assertEquals('NAZG', $iId->get(4)); + } }