Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Math Laravel Package

brick/math

Arbitrary-precision math for PHP. Work with big integers, decimals and rationals reliably, with automatic acceleration via GMP or BCMath when available. PHP 8.2+ supported. Stable 0.x release cycles suitable for production.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Precision-Critical Use Cases: Ideal for financial systems (e.g., exact monetary calculations), cryptographic operations, scientific computing, or any domain requiring arbitrary-precision arithmetic (e.g., actuarial models, high-frequency trading).
  • Laravel Compatibility: Seamlessly integrates with PHP 8.2+ Laravel applications, especially those handling:
    • Monetary values (avoiding floating-point rounding errors).
    • Large integers (e.g., hashing, encryption, or IDs).
    • Rational numbers (e.g., probability calculations, ratios).
  • Immutability: Aligns with Laravel’s functional programming patterns (e.g., collections, query builders) by ensuring thread-safe, predictable operations.

Integration Feasibility

  • Minimal Boilerplate: Composer installation (composer require brick/math) and factory methods (BigInteger::of(), BigDecimal::of()) reduce integration complexity.
  • Extension Agnosticism: Falls back gracefully to PHP’s native BCMath/GMP if extensions are unavailable (though performance degrades).
  • Laravel Service Container: Can be bound as a singleton or resolved via dependency injection (e.g., app()->make(BigInteger::class)).
  • Database/ORM Integration: Works with Laravel Eloquent via accessors/mutators (e.g., getPrecisionAttribute()) or raw queries (e.g., BigDecimal::of($row->amount)).

Technical Risk

  • Breaking Changes: Versioning follows 0.x.y with backward-incompatible releases (e.g., 0.17.0 removed deprecated methods). Lock to a patch version (^0.17) to mitigate risk.
  • Performance Overhead: Pure-PHP mode (no GMP/BCMath) is ~100x slower for large operations. Benchmark critical paths pre-integration.
  • Floating-Point Pitfalls: Explicitly avoid float inputs (use string or fromFloatExact()) to prevent silent precision loss.
  • Serialization: Safe for cross-machine use, but test deserialization in Laravel’s cache/queue systems if leveraged.

Key Questions

  1. Precision Requirements:
    • What’s the maximum scale/precision needed (e.g., 100 decimal places for currency)?
    • Are there edge cases (e.g., division by zero, overflow) that require custom exception handling?
  2. Performance Constraints:
    • Will GMP/BCMath be available in production? If not, are pure-PHP operations acceptable?
    • Are there hot paths (e.g., real-time calculations) where this could introduce latency?
  3. Data Flow:
    • How will BigNumber objects interact with Laravel’s type system (e.g., JSON serialization, API responses)?
    • Will they replace native PHP types (e.g., int, float) entirely, or coexist?
  4. Testing:
    • Are there existing tests for floating-point edge cases (e.g., 0.1 + 0.2) that need updating?
    • Should PHPStan’s extension be adopted for static analysis?
  5. Migration Path:
    • Which legacy calculations (e.g., bcmath()) will be replaced, and what’s their current precision?
    • Are there third-party libraries (e.g., moneyphp/money) that could conflict?

Integration Approach

Stack Fit

  • PHP 8.2+ Laravel: Native support; no polyfills needed.
  • Dependencies:
    • Optional: GMP/BCMath for performance (auto-detected).
    • Conflicts: None (isolated namespace Brick\Math).
  • Tooling:
    • PHPStan: Use simPod/phpstan-brick-math for exception type narrowing.
    • IDE Support: Modern IDEs (PHPStorm, VSCode) auto-complete methods via PHPDoc.

Migration Path

  1. Assessment Phase:
    • Audit existing code for floating-point operations (e.g., +, /, round()).
    • Identify critical paths (e.g., financial calculations, hashing).
  2. Pilot Integration:
    • Replace a single high-risk calculation (e.g., bcdiv()) with BigDecimal::dividedBy().
    • Test edge cases (e.g., 1/3, 0.1 + 0.2).
  3. Incremental Rollout:
    • Phase 1: Replace float/int in models/services with BigDecimal/BigInteger. Example:
      // Before
      $total = $order->items->sum(fn ($item) => $item->price * $item->quantity);
      
      // After
      $total = BigDecimal::sum(
          ...$order->items->map(fn ($item) =>
              BigDecimal::of($item->price)->multipliedBy($item->quantity)
          )
      );
      
    • Phase 2: Update database schemas (if storing arbitrary-precision values as string or json).
    • Phase 3: Replace legacy math functions (e.g., bcmath, gmp) in libraries.
  4. Fallback Strategy:
    • Use feature flags to toggle between old/new implementations during testing.

Compatibility

  • Laravel Ecosystem:
    • Eloquent: Store BigNumber as JSON or use accessors:
      protected $casts = [
          'amount' => BigDecimal::class,
      ];
      
    • APIs: Serialize to strings or JSON (implements JsonSerializable).
    • Queues/Cache: Supports serialization/deserialization.
  • Third-Party Libraries:
    • Money Libraries: Use BigDecimal as the underlying precision engine (e.g., wrap brick/math in a Money class).
    • Math Libraries: Replace math.php or phpmath with brick/math for consistency.

Sequencing

  1. Core Services: Start with domain services handling critical calculations.
  2. Database Layer: Update models/views last (to avoid breaking changes).
  3. APIs: Ensure responses use consistent precision (e.g., always return string for BigDecimal).
  4. Tests: Rewrite floating-point assertions to use BigDecimal::equals() or isEqualTo().

Operational Impact

Maintenance

  • Dependency Management:
    • Lock to a patch version (^0.17) to avoid breaking changes.
    • Monitor GitHub for deprecations (e.g., RoundingMode constants).
  • Documentation:
    • Update internal docs to reflect BigNumber usage patterns (e.g., "Use BigDecimal for all monetary values").
    • Add examples for common operations (e.g., "How to round to 2 decimal places").
  • Tooling:
    • Add brick/math to CI checks (e.g., PHPUnit, Pest).
    • Configure PHPStan to enforce BigNumber usage where needed.

Support

  • Debugging:
    • Leverage MathException for centralized error handling.
    • Use toString() for logging (e.g., logger()->debug($bigDecimal->toString())).
  • Performance Tuning:
    • Profile pure-PHP vs. GMP/BCMath modes in production.
    • Consider caching frequent calculations (e.g., BigInteger::sqrt() results).
  • User Education:
    • Train developers on:
      • Avoiding float inputs.
      • Chaining methods for readability.
      • Handling rounding modes explicitly.

Scaling

  • Performance:
    • GMP/BCMath: Handles millions of operations/sec (benchmark with brick/math’s built-in tests).
    • Pure PHP: Degrades linearly with input size; avoid for high-throughput systems.
  • Memory:
    • BigNumber objects are immutable and lightweight (no overhead beyond storage).
    • Large numbers (e.g., 10,000-digit integers) may increase memory usage; test with expected workloads.
  • Concurrency:
    • Thread-safe (immutable objects); safe for Laravel’s request/queue workers.

Failure Modes

Scenario Risk Mitigation
GMP/BCMath unavailable Performance degradation Fallback to pure PHP; monitor with APM tools.
Invalid inputs NumberFormatException Validate inputs early (e.g., regex for BigDecimal strings).
Division by zero DivisionByZeroException Use try-catch or guard clauses (e.g., if ($denominator->isZero())).
Rounding errors Silent precision loss Enforce RoundingMode::Unnecessary where exactness is critical.
Serialization issues Corrupted data Test cross-machine serialization (e.g., cache/queue systems).
Version upgrades Breaking changes Pin to patch versions; test upgrades in staging.

Ramp-Up

  • Onboarding:
    • Developers: Provide a cheat sheet for common operations (e.g., `BigDecimal::
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport