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 Autoload Override Laravel Package

adriansuter/php-autoload-override

Override fully qualified global function calls inside class methods so you can mock them in tests. Works with PHP 8.2+ and Composer PSR-4 autoloading; integrates via a PHPUnit bootstrap using OverrideFactory to map functions (e.g., rand) to real implementations.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Target Use Case: Ideal for unit testing in Laravel/PHP applications where deterministic control over global functions (e.g., \rand(), \time(), \file_get_contents()) is required. Fits seamlessly into Laravel’s testing ecosystem (PHPUnit).
  • Laravel Compatibility:
    • Works with Laravel’s PSR-4 autoloading (default in Laravel 5.5+).
    • Integrates with Laravel’s bootstrap process (e.g., tests/bootstrap.php or phpunit.xml).
    • No conflicts with Laravel’s service container or Facades (targets global functions only).
  • Alternatives:
    • Laravel’s built-in Mockery or PHPUnit mocks for class methods.
    • Monkey-patching (e.g., setmock() in older PHPUnit) for global functions.
    • Trait-based overrides (less elegant for global functions).
    • This package is the most maintainable and explicit solution for global function mocking.

Integration Feasibility

  • Low Friction:
    • Install via Composer (--dev dependency).
    • Configure in test bootstrap (e.g., tests/bootstrap.php or phpunit.xml).
    • Zero runtime overhead in production (only active during tests).
  • Laravel-Specific Considerations:
    • Artisan Commands: Can override global functions in testable commands (e.g., mocking \time() in a scheduled task test).
    • Service Providers: Override functions used in provider booting (e.g., \file_exists() in disk checks).
    • Facades: Indirectly useful for testing facade helpers that rely on global functions.
  • Limitations:
    • No support for PSR-0 (irrelevant for Laravel, which uses PSR-4).
    • Static analysis tools (e.g., Psalm, PHPStan) may flag modified AST as "unexpected" (mitigate with @phpstan-ignore-next-line).
    • Global state: Overrides affect all classes in the target namespace (use granular forClass() to limit scope).

Technical Risk

Risk Area Severity Mitigation Strategy
Test Flakiness Medium Ensure MockRegistry::reset() is called in tearDown() to avoid bleed-over.
Performance Low Overhead only during test execution (AST parsing is minimal).
Tooling Conflicts Low Explicitly document overrides in test classes; ignore modified files in static analyzers.
Laravel-Specific Medium Test with Laravel’s test helpers (e.g., refreshDatabase()) to ensure no conflicts.
Future PHP Versions Low Package supports PHP 8.2+; Laravel drops PHP 8.1 in v10.x.

Key Questions for TPM

  1. Scope of Adoption:
    • Will this replace existing global function mocking (e.g., manual setmock()) across the entire codebase, or only in specific modules?
    • Impact: Broad adoption requires documenting all global function dependencies in tests.
  2. Testing Strategy:
    • How will this integrate with Laravel’s testing utilities (e.g., createMock(), partialMock())? Will it reduce reliance on these?
    • Impact: May simplify tests for classes heavily using global functions (e.g., \str_random()).
  3. CI/CD Impact:
    • Will test suites run slower due to AST parsing? Benchmark with a representative test suite.
    • Impact: Likely negligible unless overriding thousands of classes.
  4. Maintenance:
    • How will the team track which global functions are overridden? Consider adding a comment header in test files (e.g., // @override \rand()).
    • Impact: Prevents "override drift" where tests silently rely on mocked behavior.
  5. Alternatives:
    • For Laravel-specific global functions (e.g., \Hash::make()), is there a Facade-based alternative?
    • Impact: This package is still the best for true global functions (e.g., \file_get_contents()).

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • PHPUnit: Native integration via MockRegistry (recommended over manual overrides).
    • Pest: Works with Pest’s test lifecycle (use beforeEach/afterEach for setup/teardown).
    • Laravel Mix: No impact (targets PHP code, not assets).
    • Queues/Jobs: Override global functions in job tests (e.g., mocking \time() for delayed jobs).
  • Non-Laravel Dependencies:
    • Symfony Components: Override global functions in tests for Symfony bundles (e.g., \str_replace()).
    • Carbon: Mock \time() for deterministic Carbon tests.
  • Avoid:
    • Overriding Laravel’s internal globals (e.g., $app, app()) unless absolutely necessary.

Migration Path

  1. Pilot Phase:
    • Start with one module (e.g., a service with \rand() dependencies).
    • Replace manual mocking (e.g., setmock()) with php-autoload-override.
    • Example:
      // Before: Manual mocking
      \Mockery::mock('function', '\rand')->andReturn(42);
      
      // After: Using OverrideFactory
      OverrideFactory::create()
          ->forClass(MyService::class, ['rand' => \rand(...)])
          ->apply($classLoader);
      
  2. Gradual Rollout:
    • Add overrides to test bootstrap (tests/bootstrap.php).
    • Use OverrideFactory::build() for reusable test cases (e.g., AbstractTestCase).
  3. Full Adoption:
    • Replace all global function mocks in test suites.
    • Document overridden functions in test class headers (e.g., // Overrides: \rand, \time).

Compatibility

Component Compatibility Notes
Laravel 10.x/11.x High PHP 8.2+ support aligns with Laravel’s requirements.
PHPUnit 9.x/10.x High Works with PHPUnit’s bootstrap system.
Pest 2.x High Integrates with Pest’s hooks.
Static Analyzers Medium May flag modified AST; suppress warnings or whitelist test files.
Xdebug High No impact on debugging.
Custom Autoloaders Low Only works with Composer’s PSR-4 autoloader.

Sequencing

  1. Phase 1: Test Infrastructure
    • Configure OverrideFactory in tests/bootstrap.php.
    • Add MockRegistry::reset() to base test classes.
  2. Phase 2: Module-Specific Overrides
    • Migrate high-impact test classes (e.g., those using \rand(), \time()).
    • Example: Replace setmock('\rand') with MockRegistry::set(MyClass::class, 'rand', 42).
  3. Phase 3: CI/CD Validation
    • Run tests with the new setup to catch bleed-over effects.
    • Add a pre-commit hook to validate no global functions are mocked outside tests.
  4. Phase 4: Documentation
    • Update testing guidelines to include override patterns.
    • Example:
      ## Testing Global Functions
      Use `php-autoload-override` to mock `\rand()`, `\time()`, etc.
      ```php
      // tests/bootstrap.php
      OverrideFactory::create()
          ->forClass(MyClass::class, ['rand' => \rand(...)])
          ->apply($classLoader);
      

Operational Impact

Maintenance

  • Pros:
    • Centralized configuration: Overrides defined in bootstrap.php or base test classes.
    • No runtime cost: Zero impact in production.
    • Explicit dependencies: Clear mapping of global functions to test classes.
  • Cons:
    • Test-specific complexity: Requires understanding of MockRegistry and OverrideFactory.
    • Static analysis noise: May require suppressing warnings for modified AST.
  • Mitigations:
    • Use IDE plugins (e.g., PHPStorm) to navigate to override definitions.
    • Add pre-commit checks to detect unreset mocks (e.g., MockRegistry::reset() missing in tearDown()).

Support

  • Common Issues:
    • Mock bleed-over: Tests affecting each other due to missing reset().
      • Fix: Enforce tearDown() in base test classes.
    • Unexpected overrides: Overriding functions in unrelated classes.
      • Fix: Use
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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