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

Bcmath Compat Laravel Package

phpseclib/bcmath_compat

BCMath compatibility layer for phpseclib, providing pure-PHP replacements for bcmath functions when the ext-bcmath extension isn’t available. Helps ensure consistent big integer math support across environments for cryptography and related operations.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:

    composer require phpseclib/bcmath_compat
    

    Add to composer.json under require or require-dev if only needed for testing.

  2. Autoloading: The package auto-registers when installed. No manual require or service provider setup is needed.

  3. First Use Case: Replace native bcmath calls in a script or library:

    // Before (requires bcmath extension)
    $result = bcadd('1.23456789', '9.87654321', 10);
    
    // After (works with or without bcmath)
    $result = bcadd('1.23456789', '9.87654321', 10);
    

    Test in a shared hosting environment where bcmath is disabled.


Implementation Patterns

Workflows

  1. Fallback Strategy:

    • Use bcmath_compat as a drop-in replacement for bcmath in libraries or applications.
    • Example: Wrap bc* functions in a helper to auto-fallback:
      if (!extension_loaded('bcmath')) {
          require 'vendor/phpseclib/bcmath_compat/bcmath.php';
      }
      
  2. Cryptography Use Cases:

    • Leverage for large integer operations (e.g., RSA key generation, hashing):
      $modulus = bcpowmod('2', '1024', '12345678901234567890'); // Modular exponentiation
      
  3. Precision Control:

    • Explicitly set scale for operations to avoid floating-point quirks:
      $total = bcadd('1.1', '2.2', 2); // Result: 3.30 (not 3.3)
      
  4. Testing:

    • Mock bcmath in unit tests by requiring the compat layer:
      // In PHPUnit setup
      require 'vendor/phpseclib/bcmath_compat/bcmath.php';
      

Integration Tips

  • Laravel-Specific:

    • Use in AppServiceProvider to ensure bcmath functions are available globally:
      public function boot() {
          if (!extension_loaded('bcmath')) {
              require app_path('vendor/phpseclib/bcmath_compat/bcmath.php');
          }
      }
      
    • Cache the loaded state to avoid repeated checks:
      if (!app()->bound('bcmath_loaded')) {
          app()->singleton('bcmath_loaded', function () {
              if (!extension_loaded('bcmath')) {
                  require app_path('vendor/phpseclib/bcmath_compat/bcmath.php');
              }
              return true;
          });
      }
      
  • Performance Note:

    • Pure PHP implementations are slower than native bcmath. Benchmark critical paths if performance is a concern.

Gotchas and Tips

Pitfalls

  1. Precision Limits:

    • The compat layer may handle very large numbers differently than native bcmath. Test edge cases (e.g., bcdiv('1', '3', 100)).
    • Avoid operations with >10,000 decimal places for performance reasons.
  2. Floating-Point Behavior:

    • Results may vary slightly from native bcmath due to underlying PHP gmp/bcmath emulation. Validate outputs in financial or scientific apps.
  3. Thread Safety:

    • The compat layer is stateless but may interfere with other bcmath-dependent libraries if loaded multiple times. Use a single require per app.
  4. Error Handling:

    • Native bcmath throws warnings for invalid operations (e.g., bcdiv('1', '0')). The compat layer may return false or null instead. Normalize errors:
      $result = bcdiv($a, $b, $scale);
      if ($result === false) {
          throw new \RuntimeException("Division by zero or invalid scale");
      }
      

Debugging

  • Verify Compatibility:

    • Check if functions are loaded:
      if (!function_exists('bcadd')) {
          require 'vendor/phpseclib/bcmath_compat/bcmath.php';
      }
      
    • Compare outputs with native bcmath (if available) for critical paths.
  • Performance Profiling:

    • Use Xdebug to compare execution time of bcmath vs. compat layer in production-like environments.

Extension Points

  1. Custom Functions:

    • Extend the compat layer by adding your own bc* functions to the included bcmath.php file (e.g., bcpow):
      if (!function_exists('bcpow')) {
          function bcpow($x, $y, $scale = 0) {
              return bcpowmod($x, $y, '1', $scale);
          }
      }
      
  2. Configuration:

    • Override default precision settings by modifying the bcmath.php file before requiring it:
      define('BCMATH_SCALE', 20); // Set global scale
      require 'vendor/phpseclib/bcmath_compat/bcmath.php';
      
  3. Fallback Logic:

    • Implement a trait or helper to dynamically switch between native and compat layers:
      trait BcMathFallback {
          public function bcadd($x, $y, $scale = 0) {
              return extension_loaded('bcmath') ? bcadd($x, $y, $scale) : \bcadd($x, $y, $scale);
          }
      }
      
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