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 Steps

  1. Installation

    composer require php-standard-library/math
    

    Ensure your composer.json includes:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Math\\": "vendor/php-standard-library/math/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Replace loose arithmetic in a Laravel controller or service:

    use Math\Add;
    use Math\Division;
    
    // Example: Calculate tax
    $tax = Division::safeDivide(Add::calculate($subtotal, $shipping), 100);
    
  3. Where to Look First

    • Core Classes: Math\Add, Math\Subtract, Math\Multiply, Math\Division
    • Advanced Math: Math\SquareRoot, Math\Logarithm, Math\Factorial
    • Validation: Math\Range, Math\TypeGuard
    • Error Handling: Math\Exceptions\* (e.g., DivisionByZeroException)
    • Documentation: Inspect src/ for method signatures and @throws annotations.

Implementation Patterns

Laravel-Specific Workflows

  1. Service Layer Integration

    namespace App\Services;
    
    use Math\Add;
    use Math\Division;
    
    class PricingService {
        public function calculateTotal(float $basePrice, float $taxRate, int $quantity): float
        {
            $subtotal = Division::safeDivide(
                Add::calculate($basePrice, $taxRate),
                100
            );
            return Add::calculate($subtotal, $quantity);
        }
    }
    
  2. Model Observers/Accessors

    // app/Models/Product.php
    public function getDiscountedPriceAttribute(): float
    {
        return Math\Subtract::calculate(
            $this->price,
            Math\Division::safeDivide($this->discount_percentage, 100)
        );
    }
    
  3. Request Validation

    // app/Http/Requests/StoreOrderRequest.php
    use Math\Range;
    use Illuminate\Validation\Rule;
    
    public function rules(): array
    {
        return [
            'quantity' => [
                'required',
                Rule::function('valid_quantity')->then(function ($attribute, $value) {
                    Range::validate($value, 1, 1000);
                    return true;
                }),
            ],
        ];
    }
    
  4. Middleware for Input Sanitization

    // app/Http/Middleware/SanitizeNumericInput.php
    use Math\TypeGuard;
    use Closure;
    
    public function handle($request, Closure $next)
    {
        foreach ($request->all() as $key => $value) {
            if (TypeGuard::isNumeric($value)) {
                $request->merge([$key => (float) $value]);
            }
        }
        return $next($request);
    }
    
  5. Artisan Commands

    // app/Console/Commands/CalculateStats.php
    use Math\Mean;
    use Math\StandardDeviation;
    
    protected function handle()
    {
        $data = [1, 2, 3, 4, 5];
        $mean = Mean::calculate($data);
        $stdDev = StandardDeviation::calculate($data, $mean);
        $this->info("Mean: {$mean}, Std Dev: {$stdDev}");
    }
    
  6. Database Query Extensions

    // Custom query builder extension
    use Illuminate\Database\Query\Builder;
    use Math\SquareRoot;
    
    Builder::macro('sqrt', function ($column) {
        return $this->selectRaw("sqrt({$column}) as sqrt_{$column}");
    });
    
    // Usage:
    $results = DB::table('products')
        ->select('id', 'area')
        ->sqrt('area')
        ->get();
    

Testing Patterns

// tests/Unit/MathOperationsTest.php
use Math\Division;
use Math\Exceptions\DivisionByZeroException;
use PHPUnit\Framework\TestCase;

class MathOperationsTest extends TestCase {
    public function testSafeDivision()
    {
        $this->assertEquals(2, Division::safeDivide(10, 5));
        $this->assertNull(Division::safeDivide(10, 0));
    }

    public function testDivisionThrowsException()
    {
        $this->expectException(DivisionByZeroException::class);
        Division::divide(10, 0);
    }
}

Gotchas and Tips

Pitfalls

  1. Strict Typing Overhead

    • Issue: Methods like Math\SquareRoot::calculate() expect float but may throw InvalidArgumentException for non-numeric inputs.
    • Fix: Use Math\TypeGuard::isNumeric() or Math\Range::validate() pre-calculation.
  2. Floating-Point Precision

    • Issue: Math\Division::safeDivide(1, 3) returns 0.33333333333333 (not exact).
    • Fix: Use bcmath or gmp for financial precision:
      $result = gmp_div_q($a, $b); // Exact integer division
      
  3. Exception Handling

    • Issue: Math\Factorial::calculate(1000) may throw Math\OverflowException.
    • Fix: Set limits:
      Math\Factorial::setMaxInput(100); // Global config
      
  4. Laravel Caching Quirks

    • Issue: Cached results of Math\* functions may not serialize properly (e.g., null from safeDivide).
    • Fix: Exclude math ops from caching or use serialize():
      Cache::put('key', serialize(Math\Add::calculate($a, $b)), $seconds);
      
  5. Autoloading Conflicts

    • Issue: If Math namespace clashes with Laravel’s Math facade.
    • Fix: Use fully qualified names:
      \Math\Add::calculate($a, $b); // Explicit namespace
      
  6. Performance in Loops

    • Issue: Strict typing adds overhead in tight loops (e.g., batch processing).
    • Fix: Benchmark and optimize:
      // Before (slow)
      foreach ($data as $item) {
          $result = Math\Add::calculate($item['a'], $item['b']);
      }
      
      // After (faster for trusted data)
      foreach ($data as $item) {
          $result = $item['a'] + $item['b']; // Native PHP
      }
      

Debugging Tips

  1. Enable Strict Typing Add to php.ini or .php.ini:

    strict_types=1
    

    Or in composer.json:

    "config": {
        "platform": {
            "php": "8.1",
            "ext-bcmath": "1.0"
        }
    }
    
  2. Log Exceptions

    try {
        $result = Math\Logarithm::calculate(-1);
    } catch (Math\Exceptions\InvalidInputException $e) {
        \Log::error("Math error: {$e->getMessage()}", ['input' => [-1]]);
        throw new \RuntimeException('Invalid logarithm input');
    }
    
  3. Static Analysis Use PHPStan to catch type issues early:

    vendor/bin/phpstan analyse --level=7 src/
    
  4. Common Edge Cases

    Function Edge Case Fix
    Math\SquareRoot Negative input Use Math\Range::validate()
    Math\Division Division by zero Use safeDivide()
    Math\Factorial Large inputs (>20) Set setMaxInput()
    Math\Logarithm Non-positive input Validate with Range

Configuration Quirks

  1. Global Settings

    // Configure max factorial input (default: 20)
    Math\Factorial::setMaxInput(100);
    
    // Enable/disable exceptions (default: true)
    Math\Config::setThrowExceptions(false);
    
  2. Laravel Service Provider

    // app/Providers/AppServiceProvider.php
    use Math\Config;
    
    public function boot()
    {
        Config::setThrowExceptions(env('MATH_THROW_EXCEPTIONS', true));
    }
    
  3. Environment-Specific Behavior

    # .env
    MATH_THROW_EXCEPTIONS=false
    MATH_FACTORIAL_MAX_INPUT=5
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope