@@ -56,38 +56,7 @@ public static function fromRandom(int $length = 16, ?string $alphabet = null): s
5656 throw new InvalidArgumentException ('The length of the alphabet must in the [2^1, 2^56] range. ' );
5757 }
5858
59- if (\PHP_VERSION_ID >= 80300 ) {
60- return new static ((new Randomizer ())->getBytesFromString ($ alphabet , $ length ));
61- }
62-
63- $ ret = '' ;
64- while ($ length > 0 ) {
65- $ urandomLength = (int ) ceil (2 * $ length * $ bits / 8.0 );
66- $ data = random_bytes ($ urandomLength );
67- $ unpackedData = 0 ;
68- $ unpackedBits = 0 ;
69- for ($ i = 0 ; $ i < $ urandomLength && $ length > 0 ; ++$ i ) {
70- // Unpack 8 bits
71- $ unpackedData = ($ unpackedData << 8 ) | \ord ($ data [$ i ]);
72- $ unpackedBits += 8 ;
73-
74- // While we have enough bits to select a character from the alphabet, keep
75- // consuming the random data
76- for (; $ unpackedBits >= $ bits && $ length > 0 ; $ unpackedBits -= $ bits ) {
77- $ index = ($ unpackedData & ((1 << $ bits ) - 1 ));
78- $ unpackedData >>= $ bits ;
79- // Unfortunately, the alphabet size is not necessarily a power of two.
80- // Worst case, it is 2^k + 1, which means we need (k+1) bits and we
81- // have around a 50% chance of missing as k gets larger
82- if ($ index < $ alphabetSize ) {
83- $ ret .= $ alphabet [$ index ];
84- --$ length ;
85- }
86- }
87- }
88- }
89-
90- return new static ($ ret );
59+ return new static ((new Randomizer ())->getBytesFromString ($ alphabet , $ length ));
9160 }
9261
9362 public function bytesAt (int $ offset ): array
0 commit comments