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 rational numbers via a clean OOP API. Optimized with GMP or BCMath when available, with automatic runtime selection. Requires PHP 8.2+ (older versions available).

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Precision-Critical Use Cases: Ideal for financial calculations, cryptography, scientific computing, or any domain requiring exact arithmetic (e.g., currency, actuarial models, or blockchain).
  • Laravel Compatibility: Seamlessly integrates with PHP 8.2+ (Laravel 10+). No framework-specific conflicts; works as a standalone library.
  • Performance Considerations:
    • Leverages GMP/BCMath for acceleration (auto-selected at runtime). Critical for high-throughput systems (e.g., batch processing).
    • Pure-PHP fallback ensures portability but may impact performance in CPU-bound workflows.
  • Immutability Design: Aligns with Laravel’s immutable patterns (e.g., Carbon, UUID) but requires explicit adoption (e.g., avoiding mutable state in services).

Integration Feasibility

  • Minimal Boilerplate: Factory methods (BigInteger::of(), BigDecimal::of()) simplify adoption. No ORM or service container integration needed.
  • Type Safety: PHPStan extension improves static analysis (e.g., catching RoundingNecessaryException early).
  • Serialization: Safe for distributed systems (e.g., queues, caching) even across environments with mismatched PHP extensions.

Technical Risk

  • Breaking Changes: Versioning follows 0.x.y with backward-incompatible jumps (e.g., 0.15.0 removed float support). Lock to ^0.17 to mitigate.
  • Floating-Point Pitfalls: BigDecimal::fromFloatExact() exposes IEEE-754 quirks (e.g., 0.10.10000000000000000555...). Requires explicit handling in user-facing APIs.
  • Performance Overhead: GMP/BCMath dependency may complicate deployment (e.g., Docker images, serverless). Benchmark critical paths pre-release.
  • Edge Cases: Division/modulo operations throw exceptions (e.g., RoundingNecessaryException). Requires robust error handling in business logic.

Key Questions

  1. Precision Requirements:
    • Are we replacing float/int for exactness, or supplementing them (e.g., for display only)?
    • Example: Financial rounding rules (e.g., RoundingMode::Bankers) vs. scientific precision.
  2. Performance Tradeoffs:
    • Can we enable GMP/BCMath in all environments, or must we support pure-PHP mode?
    • Benchmark against alternatives (e.g., php-gmp, bcmath native functions).
  3. Error Handling Strategy:
    • Should MathException be mapped to Laravel’s Handler (e.g., convert to HttpResponse)?
    • Example: Return 422 Unprocessable Entity for RoundingNecessaryException in APIs.
  4. Testing Coverage:
    • How to validate edge cases (e.g., BigInteger::nthRoot(-1, 2)) in CI?
    • Use property-based testing (e.g., PestPHP) for arithmetic correctness.
  5. Dependency Management:
    • Should we pin brick/math to a specific patch version (e.g., 0.17.2) or use ^0.17?
    • Monitor for breaking changes in minor releases (e.g., 0.18.0).

Integration Approach

Stack Fit

  • PHP 8.2+: Native support for named arguments and union types simplifies API usage (e.g., BigDecimal::dividedBy(string|BigDecimal $divisor, int $scale)).
  • Laravel Ecosystem:
    • Validation: Use brick/math in FormRequest rules (e.g., validate BigDecimal precision).
    • Testing: Replace assertEquals(0.1 + 0.2, 0.3) with BigDecimal assertions.
    • Console: Ideal for CLI tools requiring exact arithmetic (e.g., data migration scripts).
  • Third-Party Libraries:
    • MoneyPHP: Replace Money with BigDecimal for arbitrary-precision currency.
    • Carbon: Combine with BigInteger for time-based calculations (e.g., Unix timestamps with millisecond precision).

Migration Path

  1. Phase 1: Proof of Concept
    • Replace a single float-intensive class (e.g., OrderTotalCalculator) with BigDecimal.
    • Test edge cases (e.g., 0.1 + 0.2 != 0.3).
  2. Phase 2: Core Services
    • Migrate financial services (e.g., PaymentService, TaxCalculator).
    • Use BigDecimal::fromFloatShortest() for legacy float inputs.
  3. Phase 3: API Contracts
    • Update JSON:API schemas to accept string for numeric fields (e.g., "amount": "123.456").
    • Add middleware to validate BigDecimal inputs (e.g., reject 1.23e+20).
  4. Phase 4: Database
    • Store BigDecimal as string in PostgreSQL (use numeric for hybrid approaches).
    • Avoid float/decimal columns to prevent rounding.

Compatibility

  • Backward Compatibility:
    • Wrap existing float/int logic in adapters (e.g., FloatToBigDecimal::convert()).
    • Example:
      class LegacyFloatAdapter {
          public static function toBigDecimal(float $value): BigDecimal {
              return BigDecimal::fromFloatExact($value);
          }
      }
      
  • Extension Dependencies:
    • Document GMP/BCMath requirements in composer.json extras:
      "config": {
        "preferred-install": "dist",
        "platform-check": {
          "php": "8.2",
          "ext-gmp": "enabled",
          "ext-bcmath": "enabled"
        }
      }
      
    • Fallback: Use pure-php branch if extensions are unavailable.

Sequencing

  1. Critical Path First:
    • Start with high-impact, low-volume services (e.g., admin dashboards).
    • Avoid migrating high-throughput APIs (e.g., /checkout) until performance is validated.
  2. Testing Strategy:
    • Unit Tests: Mock BigDecimal to test rounding behavior.
    • Integration Tests: Validate database serialization/deserialization.
    • Chaos Testing: Fuzz inputs (e.g., BigInteger::of("9999999999999999999999999999999999999999999")).
  3. Rollout:
    • Feature flag config('math.use_brick_math') for gradual adoption.
    • Canary release in staging with BigDecimal logging.

Operational Impact

Maintenance

  • Dependency Updates:
    • Monitor brick/math for breaking changes (e.g., 0.18.0).
    • Use composer why-not brick/math:0.18.0 to assess risks.
  • Documentation:
    • Add internal docs for:
      • Common pitfalls (e.g., BigDecimal::of("1.01") vs. BigDecimal::of(1.01)).
      • Performance tuning (e.g., GMP vs. pure-PHP).
    • Example:
      ## Brick Math Best Practices
      - Use `BigDecimal::fromFloatShortest()` for legacy `float` inputs.
      - Avoid chaining operations in loops (e.g., `$result->plus($x)->minus($y)` creates intermediate objects).
      
  • Tooling:
    • Integrate PHPStan with simPod/phpstan-brick-math for static analysis.
    • Add custom Rector rules to migrate float to BigDecimal incrementally.

Support

  • Common Issues:
    • Rounding Errors: Users may expect 0.1 + 0.2 == 0.3. Document this explicitly.
    • Performance Bottlenecks: Pure-PHP mode may slow down batch jobs. Profile with Xdebug + Blackfire.
    • Serialization Failures: Ensure all cached/queued BigNumber instances are JSON-serializable.
  • Debugging:
    • Add a MathDebugger service to log operations:
      class MathDebugger {
          public static function log(BigNumber $number, string $operation, BigNumber|int|string $operand): void {
              \Log::debug("Math: {$number} {$operation} {$operand} = {$number->{$operation}($operand)}");
          }
      }
      
  • User Training:
    • Train devs on:
      • Immutability (e.g., $x->plus($y) vs. $x += $y).
      • Exception hierarchy (e.g., RoundingNecessaryException vs. DivisionByZeroException).

Scaling

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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony