diff --git a/src/AbService.php b/src/AbService.php index 06d3879..633c011 100644 --- a/src/AbService.php +++ b/src/AbService.php @@ -109,10 +109,10 @@ public function getVariant(string $experiment): string public function getHash(string $uid, string $experiment): float { - $hex = substr(hash('sha256', $uid . $experiment), 0, 16); + $hex = substr(hash('sha256', $uid . $experiment), 0, 15); $int = hexdec($hex); - return $int / 0xFFFFFFFFFFFFFFFF; + return $int / 2 ** 60; } public function chooseVariant(float $hash, array $variants): string @@ -122,8 +122,9 @@ public function chooseVariant(float $hash, array $variants): string $names = array_keys($variants); $weights = array_values($variants); + $nameCount = count($names); - for ($i = 0; $i < count($names) -1; $i++) { + for ($i = 0; $i < $nameCount - 1; $i++) { $sum += $weights[$i]; if ($hash < $sum) { diff --git a/test/AbServiceTest.php b/test/AbServiceTest.php index ea08883..52bd2a8 100644 --- a/test/AbServiceTest.php +++ b/test/AbServiceTest.php @@ -96,7 +96,7 @@ public function testGetVariant(): void public function testGetVariantDistributed(): void { $this->markTestSkipped("takes a while"); - + $iterations = 1000000; $delta = $iterations / 500; // 0.2% difference