settleup / can-make-or-fake
A simple helper for making classes easily instantiated and mocked.
Fund package maintenance!
Requires
- php: ^8.4
- illuminate/contracts: ^12.0||^13.0
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.8
- orchestra/testbench: ^11.0||^10.0
- pestphp/pest: ^4.0
- pestphp/pest-plugin-arch: ^4.0
- pestphp/pest-plugin-laravel: ^4.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
README
A lightweight Laravel trait that gives any class a make() static constructor (resolved through the container) and a fake() method for easy test mocking.
Installation
composer require settleup/can-make-or-fake
Usage
Add the CanMakeOrFake trait to any class:
use SettleUp\CanMakeOrFake\CanMakeOrFake; class PriceCalculator { use CanMakeOrFake; public function calculate(int $quantity, int $unitPrice): int { return $quantity * $unitPrice; } }
Resolving instances with make()
make() resolves the class through Laravel's service container, so any constructor dependencies are automatically injected:
$calculator = PriceCalculator::make(); $total = $calculator->calculate(quantity: 3, unitPrice: 500); // 1500
Faking in tests with fake()
fake() creates a Mockery partial mock and binds it into the container. Any subsequent call to make() (or container resolution) will return the mock:
use Mockery\MockInterface; PriceCalculator::fake(function (MockInterface $mock) { $mock->shouldReceive('calculate')->andReturn(0); }); // Anywhere in your application that resolves PriceCalculator will now get the fake $calculator = PriceCalculator::make(); $calculator->calculate(3, 500); // 0
Because fake() creates a partial mock, any methods you don't explicitly mock will still call the real implementation.
Conditionable
The trait includes Laravel's Conditionable trait, so you can use when() and unless():
$calculator = PriceCalculator::make(); $calculator->when($applyDiscount, function (PriceCalculator $calc) { // ... });
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.