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

Php Percent Laravel Package

assoconnect/php-percent

Small PHP library to represent and work with percentages in a way that pairs well with MoneyPHP, based on Frederik Bosch’s proposal. Install via Composer and use the PHPDoc-documented API to apply percent calculations safely alongside Money values.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Use Case Alignment: The assoconnect/php-percent package (v1.1.5) remains ideal for financial applications in Laravel, particularly for percentage-based calculations tied to MoneyPHP. The new release introduces type safety improvements (PHPStan baseline for float return types), reinforcing its suitability for precise monetary operations like discounts, taxes, or dynamic pricing.
  • Laravel Synergy: Continues to align seamlessly with Laravel’s financial stack (e.g., laravel-money or moneyphp/money), reducing boilerplate while maintaining type safety.
  • Domain-Specific Value: The standardized PHPStan config ensures consistency in return types (e.g., float for percentage values), mitigating potential type-related bugs in complex workflows.

Integration Feasibility

  • Dependency Compatibility:
    • No breaking changes to core dependencies (MoneyPHP v3.0+ required). The PHPStan baseline is an internal tooling improvement and does not affect runtime behavior.
    • Type Safety: The package now explicitly baselines float return types, which may require updating user code if relying on implicit type coercion (e.g., int vs. float percentages).
  • API Simplicity:
    • Unchanged from prior versions. Core methods (apply(), getValue(), setValue()) remain stable.
    • Example remains valid:
      $percent = new Percent(10.5, Money::EUR(100)); // Explicit float support
      $discount = $percent->apply(); // Returns Money object for €10.50
      
  • Testing & Validation:
    • PHPStan integration enables stricter static analysis, reducing runtime type errors. Teams using PHPStan will benefit from early detection of incompatible return types.

Technical Risk

  • Low Risk:
    • No breaking changes in public API or runtime behavior. The PHPStan baseline is a developer tooling improvement.
    • Active maintenance (2026 release) and MIT license maintain stability.
  • Potential Pitfalls:
    • Float Precision: While the package now standardizes float return types, Laravel applications must still handle floating-point precision in financial contexts (e.g., rounding to 2 decimal places for currencies). Use MoneyPHP's round() or Laravel’s number_format() cautiously.
    • Type Coercion: If user code assumes Percent::getValue() returns int (e.g., for whole-number percentages), explicit casting may be needed:
      $rate = (int) $percent->getValue(); // Explicit cast for integer rates
      
    • Laravel-Specific Quirks: As before, avoid returning raw Percent objects from repositories or Blade templates to prevent type mismatches.

Key Questions

  1. Type Handling Strategy:
    • Should the team enforce int percentages (e.g., for whole numbers) or embrace float for precision (e.g., 10.5%)? Document this in a coding guideline.
  2. PHPStan Adoption:
    • Will the team adopt PHPStan’s stricter type checking? If so, update CI/CD to include the package’s baseline config.
  3. Float vs. String Percentages:
    • For user-input percentages (e.g., from APIs or forms), how will the team handle conversion from strings (e.g., "10.5%") to float/int values?
  4. Backward Compatibility:
    • Are there legacy calculations assuming int percentages that may now trigger PHPStan warnings? Audit and refactor incrementally.
  5. Alternatives:
    • Could Laravel’s native Money facade or a custom Percentage trait (with explicit type hints) achieve similar results with less abstraction?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • MoneyPHP Integration: Continues to work natively with laravel-money or moneyphp/money. No changes to integration patterns.
    • Service Layer: Best practice remains to use Percent in Laravel services (e.g., DiscountService) rather than models or controllers.
    • Blade/Views: Avoid direct instantiation; pass pre-computed Money objects.
  • Tooling:
    • PHPStan: If adopted, the package’s baseline config can be included in project-level PHPStan rules to enforce consistent return types:
      includes:
        - vendor/assoconnect/php-percent/phpstan.neon
      
    • IDE Support: PHPStan integration will improve autocomplete and error detection for Percent methods.

Migration Path

  1. Assessment Phase:
    • Audit existing percentage logic for implicit type assumptions (e.g., int vs. float). Use PHPStan to identify potential issues:
      vendor/bin/phpstan analyse --level 5
      
  2. Incremental Adoption:
    • Step 1: Replace one financial workflow (e.g., dynamic discounts) with Percent, ensuring type consistency.
    • Step 2: Update tests to use explicit type assertions (e.g., assertIsFloat($percent->getValue())).
    • Step 3: Refactor remaining logic, leveraging PHPStan to catch type mismatches early.
  3. Backward Compatibility:
    • For legacy code, create adapters to handle type coercion:
      class PercentAdapter {
          public static function fromInt(int $rate, Money $amount): Percent {
              return new Percent((float) $rate, $amount);
          }
      }
      

Compatibility

  • PHP Version: Requires PHP 8.0+ (unchanged).
  • MoneyPHP Version: Test with moneyphp/money:^3.0 to avoid deprecation issues.
  • PHPStan Version: If using PHPStan, ensure compatibility with the package’s baseline config (v1.0+ recommended).
  • Laravel Services:
    • Bind Percent to interfaces for testability, and explicitly type-hint methods to avoid ambiguity:
      interface PercentageCalculator {
          public function calculate(float $rate, Money $amount): Money;
      }
      

Sequencing

  1. Core Integration:
    • Start with a single use case (e.g., promotional discounts) to validate type safety and performance.
  2. Testing:
    • Write unit tests for Percent operations, including:
      • Float vs. int percentage inputs.
      • Edge cases (e.g., 0.0, 100.0, negative values).
      • PHPStan analysis to enforce return type consistency.
    • Example test:
      public function testFloatPercentageReturnsMoney(): void {
          $percent = new Percent(10.5, Money::EUR(100));
          $result = $percent->apply();
          $this->assertInstanceOf(Money::class, $result);
          $this->assertEquals(10.5, $percent->getValue()); // Explicit float check
      }
      
  3. Performance Benchmarking:
    • Compare execution time of Percent (with float support) vs. raw MoneyPHP for critical paths.
  4. Documentation:
    • Update internal docs to reflect float type support and PHPStan compatibility.
  5. Monitoring:
    • Log type-related warnings or errors in staging to catch edge cases (e.g., invalid float inputs).

Operational Impact

Maintenance

  • Pros:
    • Type Safety: PHPStan baseline reduces runtime type errors, improving code reliability.
    • Consistency: Standardized return types (e.g., float for percentages) across the codebase.
  • Cons:
    • Developer Overhead: Teams not using PHPStan may miss type-related improvements. Consider adding a CI check for type consistency.
    • Migration Effort: Legacy code assuming int percentages may require refactoring to accommodate floats.

Support

  • Proactive Measures:
    • Error Handling: Enhance service-layer validation to handle float/int coercion gracefully:
      public function applyDiscount(float|int $rate, Money $amount): Money {
          $percent = new Percent((float) $rate, $amount);
          return $percent->apply();
      }
      
    • Support Matrix: Document common issues (e.g., "PHPStan warnings for int percentages can be resolved by casting to float").
    • PHPStan Integration: Add a CI step to enforce the package’s baseline config:
      # .github/workflows/phpstan.yml
      jobs:
        phpstan:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - run: composer require --dev phpstan/phpstan
            - run: vendor/bin/phpstan analyse --level 5 --configuration=phpstan.neon
      

Scaling

  • Performance:
    • Low Overhead: Float support adds negligible runtime cost. Benchmark if using high-frequency calculations (e.g., bulk order processing).
    • Caching: Cache Percent results for idempotent operations (e.g., precomputed tax rates).
  • Horizontal Scaling:
    • Stateless and scalable with Laravel’s queue workers or microservices.

Failure Modes

| Failure Scenario | Impact | Mitigation | |-------------------------------------|

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.
craftcms/url-validator
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