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

Stubs Laravel Package

php-decimal/stubs

IDE and static analysis stubs for the PHP Decimal extension. Provides PHP method/function signatures to improve autocompletion and type checking without requiring the extension source. For installing the actual extension, see php-decimal/php-decimal.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Core Dependency First, install the php-decimal/php-decimal package (this package provides the actual Decimal class):

    composer require php-decimal/php-decimal
    
  2. Add Stubs Install the stubs package to enable IDE autocompletion and static analysis:

    composer require --dev php-decimal/stubs
    
  3. Trigger Stub Loading Run composer dump-autoload to ensure stubs are loaded:

    composer dump-autoload
    
  4. Verify in IDE Open a PHP file and type new \Decimal\Decimal(...)—your IDE (PHPStorm, VSCode with Intelephense) should now show method autocompletion.


First Use Case: Decimal Arithmetic

use Decimal\Decimal;

$price = new Decimal('19.99');
$taxRate = new Decimal('0.0725'); // 7.25%
$total = $price->multiply($taxRate)->add($price);

echo $total; // Outputs: 21.44 (with precision handling)

Why? Stubs ensure your IDE validates method calls like multiply() and add() without runtime errors.


Implementation Patterns

1. Type Safety with Static Analysis

  • Use with PHPStan/Psalm: Configure your static analyzer to recognize Decimal as a custom type. Example PHPStan config:

    includes:
      - vendor/php-decimal/stubs/Decimal.stub
    

    Now, tools will flag invalid operations (e.g., $decimal->concat()).

  • Return Type Declarations:

    function calculateTotal(array $items): Decimal {
        return array_reduce($items, fn(Decimal $carry, array $item) => $carry->add($item['price']), new Decimal('0'));
    }
    

2. Integration with Laravel

  • Form Request Validation: Use Decimal in validation rules (via custom rules or Illuminate\Validation\Rule):

    use Decimal\Decimal;
    
    $validator->validate([
        'price' => new Decimal($request->price),
    ], [
        'price' => ['required', function (string $attribute, mixed $value, Closure $fail) {
            if (!($value instanceof Decimal)) {
                $fail('The '.$attribute.' must be a valid decimal.');
            }
        }],
    ]);
    
  • Model Attributes: Cast attributes to Decimal in Eloquent models:

    protected $casts = [
        'price' => Decimal::class,
    ];
    

    Note: Requires custom accessors/mutators if using Laravel < 8.x.

3. Precision Handling Workflows

  • Consistent Precision: Set a default precision in a service class:

    class MoneyService {
        public function __construct(private Decimal $precision) {}
    
        public function format(Decimal $amount): string {
            return $amount->toScale($this->precision->value)->toString();
        }
    }
    

    Stubs Benefit: IDE will autocomplete toScale() and toString().

  • Avoiding Floating-Point Pitfalls: Replace float with Decimal in calculations:

    // Bad: Floating-point inaccuracy
    $total = $subtotal + ($subtotal * 0.0725);
    
    // Good: Precise arithmetic
    $total = $subtotal->add($subtotal->multiply($taxRate));
    

4. Testing

  • Mocking Decimals: Use Decimal::fromFloat() for test data:
    $this->assertEquals(
        new Decimal('19.99'),
        Decimal::fromFloat(19.99)->toScale(2)
    );
    
    Stubs Benefit: IDE shows fromFloat() as a valid static method.

Gotchas and Tips

Pitfalls

  1. Stub Loading Failures

    • Symptom: IDE shows Class 'Decimal\Decimal' not found or no autocompletion.
    • Fix:
      • Ensure composer dump-autoload is run after installing stubs.
      • For PHPStorm, go to Settings > PHP > Include Path and add:
        vendor/php-decimal/stubs
        
      • For VSCode, restart the Intelephense server (Ctrl+Shift+P > "Intelephense: Restart Server").
  2. Precision Mismatches

    • Issue: Decimal::fromFloat(0.1) may not equal new Decimal('0.1') due to floating-point representation.
    • Workaround: Use string constructors or toScale():
      $decimal = new Decimal('0.1'); // Exact
      // or
      $decimal = Decimal::fromFloat(0.1)->toScale(1);
      
  3. Static Analysis False Positives

    • Problem: PHPStan/Psalm may flag Decimal methods as undefined.
    • Solution: Explicitly include stubs in your analyzer config (see Implementation Patterns).
  4. Laravel Cache Issues

    • Scenario: After adding stubs, cached routes/views may still reference old Decimal behavior.
    • Fix: Clear Laravel cache:
      php artisan cache:clear
      php artisan view:clear
      

Tips

  1. IDE-Specific Tricks

    • PHPStorm:
      • Enable "Strict type checking" in Settings > Languages & Frameworks > PHP for better stub integration.
      • Use Ctrl+Space to trigger autocompletion after typing new Decimal(.
    • VSCode:
      • Install the "PHP Intelephense" extension and add this to settings.json:
        "intelephense.stubs": ["vendor/php-decimal/stubs"]
        
  2. Performance Considerations

    • Avoid Overusing Decimal: For simple cases (e.g., counters), stick with int. Use Decimal only for monetary/precise values.
    • Batch Operations: If processing many Decimal values, consider using Decimal::fromFloat() in bulk and converting to strings for storage (e.g., in a database).
  3. Extending Functionality

    • Custom Methods: Create a trait to add domain-specific methods:
      trait MoneyMethods {
          public function toCurrency(string $currency = 'USD'): string {
              return sprintf('%s %s', $currency, $this->toScale(2));
          }
      }
      
      Stubs Workaround: IDE won’t autocomplete trait methods—document them in PHPDoc blocks.
  4. Debugging

    • Dump Decimal Values: Use a custom dump function to inspect precision:
      function ddDecimal(Decimal $decimal) {
          dump([
              'value' => $decimal->toString(),
              'scale' => $decimal->scale(),
              'precision' => $decimal->precision(),
          ]);
      }
      
    • Common Errors:
      • Division by zero: Use Decimal::fromFloat(0) instead of new Decimal('0') for safety.
      • Invalid argument: Ensure inputs to Decimal are strings or numeric strings (e.g., '19.99' not 19.99).
  5. CI/CD Integration

    • Static Analysis: Add PHPStan/Psalm checks to your CI pipeline with stubs included:
      # Example GitHub Actions step
      - name: Run PHPStan
        run: vendor/bin/phpstan analyse --level=5 --include-paths=vendor/php-decimal/stubs src/
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky