offset = $config['offset'] ?? 0; $this->hasGmp = extension_loaded( 'gmp' ); $this->hasBcm = extension_loaded( 'bcmath' ); if ( !$this->hasGmp && !$this->hasBcm ) { throw new RuntimeException( __CLASS__ . ' requires the bcmath or gmp extension' ); } } public function getSerialIdForIndex( int $index ): string { if ( $index <= 0 ) { return (string)$index; } $offset = $this->offset; if ( $index - $offset < 0 ) { throw new OutOfBoundsException( __METHOD__ . ": The configured offset $offset is too large." ); } foreach ( self::GENERATORS as [ $g, $p ] ) { if ( $index - $offset < $p ) { return (string)( $offset + $this->powmod( $g, $index - $offset, $p ) ); } $offset += $p - 1; } throw new RuntimeException( __METHOD__ . ": The index $index is too large" ); } private function powmod( int $num, int $exponent, int $modulus ): int { if ( $this->hasGmp ) { return \gmp_intval( \gmp_powm( $num, $exponent, $modulus ) ); } elseif ( $this->hasBcm ) { return (int)\bcpowmod( (string)$num, (string)$exponent, (string)$modulus ); } else { throw new LogicException( __CLASS__ . ' requires the bcmath or gmp extension' ); } } }