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

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-standard-library/math
    

    Add to composer.json under require if not auto-loaded.

  2. First Use Case

    use Math\Math;
    
    // Basic arithmetic with type safety
    $result = Math::add(5, 3); // Returns 8 (int)
    $result = Math::divide(10, 3); // Returns 3.333... (float)
    
  3. Where to Look First

    • Core Functions: Math::add(), Math::subtract(), Math::multiply(), Math::divide()
    • Advanced Math: Math::sqrt(), Math::pow(), Math::log()
    • Type-Safe Wrappers: Math::safeDivide() (returns null on division by zero)
    • Documentation: Check src/Math.php for full method signatures and edge-case behavior.

Implementation Patterns

Workflow Integration

  1. Type-Safe Calculations

    // Laravel Service Layer Example
    public function calculateDiscount(float $price, float $percentage): float
    {
        return Math::multiply($price, Math::divide($percentage, 100));
    }
    
  2. Error Handling

    try {
        $result = Math::safeDivide(10, 0); // Returns null
    } catch (InvalidArgumentException $e) {
        // Fallback logic
    }
    
  3. Batch Operations

    $sum = 0;
    foreach ($prices as $price) {
        $sum = Math::add($sum, $price);
    }
    
  4. Laravel Facade (Optional) Create a facade for cleaner syntax:

    // app/Facades/MathFacade.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class MathFacade extends Facade {
        protected static function getFacadeAccessor() { return 'math'; }
    }
    

    Register in AppServiceProvider:

    $this->app->bind('math', function () {
        return new \Math\Math();
    });
    

    Usage:

    use App\Facades\MathFacade as Math;
    Math::add(5, 3); // Now works as a facade
    
  5. Validation Integration

    use Math\Math;
    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($request->all(), [
        'percentage' => 'required|numeric|max:100',
        'price' => 'required|numeric|min:0',
    ]);
    
    if ($validator->fails()) {
        return response()->json(['error' => $validator->errors()]);
    }
    
    $discountedPrice = Math::subtract(
        $request->price,
        Math::multiply($request->price, Math::divide($request->percentage, 100))
    );
    

Gotchas and Tips

Pitfalls

  1. Strict Typing

    • Methods like Math::sqrt() throw InvalidArgumentException for negative inputs.
    • Fix: Use Math::safeSqrt() for nullable results or validate inputs first.
  2. Floating-Point Precision

    • Math::divide(1, 3) returns 0.3333333333333333 (not 0.333...).
    • Tip: Round results explicitly if needed:
      $rounded = Math::round(Math::divide(1, 3), 2); // 0.33
      
  3. Division by Zero

    • Math::divide(10, 0) throws DivisionByZeroError.
    • Tip: Prefer Math::safeDivide() for APIs or use try-catch blocks.
  4. Large Numbers

    • Integers beyond PHP_INT_MAX may overflow silently.
    • Tip: Use Math::bigIntAdd() (if available) or GMP functions for arbitrary precision.

Debugging Tips

  1. Enable Strict Mode Add to composer.json:

    "config": {
        "platform-check": true,
        "platform": {
            "php": "8.1"
        }
    }
    

    Ensures type safety during development.

  2. Logging Edge Cases

    try {
        $result = Math::log(0);
    } catch (\Exception $e) {
        \Log::error("Math operation failed: " . $e->getMessage());
        // Fallback logic
    }
    
  3. Testing Use PHPUnit to test edge cases:

    public function testSafeDivideByZero()
    {
        $this->assertNull(Math::safeDivide(10, 0));
    }
    

Extension Points

  1. Custom Functions Extend the Math class or create a decorator:

    class ExtendedMath extends Math {
        public static function taxAmount(float $amount, float $taxRate): float
        {
            return self::multiply($amount, self::divide($taxRate, 100));
        }
    }
    
  2. Monkey-Patching (Not Recommended) Override methods in a service provider (use cautiously):

    Math::divide = function ($a, $b) {
        if ($b === 0) return null;
        return $a / $b;
    };
    
  3. Laravel Service Container Bind custom math logic:

    $this->app->extend('math', function ($app, $math) {
        $math->setPrecision(4); // Hypothetical method
        return $math;
    });
    
  4. Configuration If the package supports config (e.g., config/math.php), customize:

    'precision' => 6, // Default decimal places
    'strict_mode' => true, // Enable strict type checks
    
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