simplito/bigint-wrapper-php
Lightweight PHP wrapper for working with big integers safely beyond native limits. Provides convenient object-style operations for arithmetic, comparisons, and formatting, helping avoid overflow issues when handling large numeric IDs, counters, or financial values.
Install via Composer:
composer require simplito/bigint-wrapper-php
Begin by converting large numeric strings (e.g., IDs, financial amounts) to BigInteger objects to avoid PHP integer overflow:
use big\bigint\BigInteger;
$largeId = BigInteger::fromString('9223372036854775808'); // exceeds PHP_INT_MAX
$incremented = $largeId->add(BigInteger::fromInt(1));
echo $incremented->toString(); // "9223372036854775809"
Check the active backend (GMP or BCMath) at runtime:
echo BigInteger::getBackend(); // e.g., "gmp" or "bcmath"
This is ideal when reading BIGINT columns from MySQL/PostgreSQL or handling cryptographic values.
BIGINT columns:
class BigIntCast implements CastsAttribute
{
public function get($model, $key, $value, $attributes) {
return BigInteger::fromString($value);
}
public function set($model, $key, $value, $attributes) {
return $value instanceof BigInteger ? $value->toString() : $value;
}
}
Then apply: 'user_id' => BigIntCast::class.try {
$amount = BigInteger::fromString($request->input('amount'), 10);
} catch (\Exception $e) {
abort(422, 'Invalid numeric value');
}
cmp(), lt(), eq() for deterministic sorting/ranges—e.g., rate-limiting by timestamp IDs:
if ($requestId->gt($lastProcessedId)) { ... }
BigInteger in value objects (e.g., AccountId, CryptoAmount) to enforce domain semantics and prevent misuse:
final class CryptoAmount {
private BigInteger $value;
private function __construct(BigInteger $value) { $this->value = $value; }
public static function fromString(string $str): self { return new self(BigInteger::fromString($str)); }
public function plus(self $other): self { return new self($this->value->add($other->value)); }
// ... other operations
}
php-gmp). Always verify backend availability in staging: BigInteger::getBackend()—mismatched environments can cause subtle performance regressions.div() performs floor division. For financial decimal precision (e.g., $amount * 0.015), configure scale before operations:
BigInteger::setScale(4); // affects BCMath scale globally
$fee = BigInteger::fromString('100')->mul(BigInteger::fromString('15'))->div(BigInteger::fromString('1000'));
__toString(): Use explicit toString()—__toString() may be undefined or inconsistent across backends.$_POST['value'] to fromInt()—it first casts to PHP int (overflow risk). Always use fromString().BigInteger via dependency injection (e.g., inject a factory interface) instead of relying on static methods—avoiding heavy arithmetic in test suites.BigInteger class) and unit tests—if present. Confirm method signatures via reflection (ReflectionClass('big\bigint\BigInteger')->getMethods()).How can I help you explore Laravel packages today?