php-standard-library/math
Strictly typed math utilities for PHP with predictable, consistent error handling. Part of the PHP Standard Library project, providing reliable mathematical functions and a stable developer experience for safer numeric operations.
Strengths:
Fit for Laravel Use Cases:
Math facade or loose arithmetic operations (e.g., /, +) with typed alternatives in service layers or controllers.Misalignment:
bcmath or gmp for arbitrary-precision needs.Low Effort:
composer require with PSR-4 autoloading. No Laravel-specific configuration required.Math::add($a, $b) instead of $a + $b).Medium Effort:
Math::sqrt(-1) throws InvalidArgumentException).High Effort:
Math::factorial()).null or strings to math functions). Mitigation: Use gradual adoption with wrappers or feature flags.Math\DivisionByZero) require updates to existing error-handling logic. Mitigation: Standardize exception handling early (e.g., via middleware or base controllers).array_unpack) may require updates. Mitigation: Pin PHP version in composer.json.NaN, Infinity, and boundary values (e.g., Math::factorial(1000)). Mitigation: Use property-based testing (e.g., PestPHP) to generate edge cases.symfony/polyfill-php80 for basic math).gmp/bcmath or evaluate alternatives like php-gmp.spatie/laravel-query-builder, moneyphp/money) that could conflict or complement this? Test for compatibility.bcmath.Math::sqrt(-1)).Math\* exceptions in Laravel Horizon or Sentry for production issues.Math::round($value) instead of ROUND(column, 2) in queries).Phase 1: Validation Layer (Low Effort)
// Before
if (!is_numeric($input) || $input < 0) {
throw new InvalidArgumentException();
}
// After
Math::Range::validate($input, 0, null);
Phase 2: Core Logic (Medium Effort)
// Before (loose)
public function calculateDiscount(float $price, float $percentage) {
return $price * ($percentage / 100);
}
// After (strict)
public function calculateDiscount(float $price, float $percentage): float {
return Math::multiply($price, Math::divide($percentage, 100));
}
Phase 3: Infrastructure (High Effort)
// app/Http/Middleware/ValidateMathInputs.php
public function handle(Request $request, Closure $next) {
$request->merge([
'validated_price' => Math::Range::validate(
$request->price,
0.01,
10000
),
]);
return $next($request);
}
// app/Facades/MathFacade.php
public static function divide($a, $b) {
return Math::safeDivide($a, $b);
}
Phase 4: Testing and Optimization (Ongoing)
Math::factorial(1000)).// app/Providers/AppServiceProvider.php
public function register() {
$this->app->singleton('math', function () {
return new Math\Math();
});
}
Math facade to mirror Laravel’s Str/Arr patterns:
// app/Facades/MathFacade.php
public static function add($a, $
How can I help you explore Laravel packages today?