Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
add macroable trait to database factory
  • Loading branch information
cmgmyr committed Feb 24, 2021
commit 4bc51e4853f9810c74707ce6201aa67f03b898a4
9 changes: 8 additions & 1 deletion src/Illuminate/Database/Eloquent/Factories/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ForwardsCalls;
use Illuminate\Support\Traits\Macroable;
use Throwable;

abstract class Factory
{
use ForwardsCalls;
use ForwardsCalls, Macroable {
__call as macroCall;
}

/**
* The name of the factory's corresponding model.
Expand Down Expand Up @@ -747,6 +750,10 @@ protected static function appNamespace()
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}

if (! Str::startsWith($method, ['for', 'has'])) {
static::throwBadMethodCallException($method);
}
Expand Down
10 changes: 10 additions & 0 deletions tests/Database/DatabaseEloquentFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,16 @@ public function test_dynamic_has_and_for_methods()
$this->assertCount(2, $post->comments);
}

public function test_can_be_macroable()
{
$factory = FactoryTestUserFactory::new();
$factory->macro('getFoo', function () {
return 'Hello World';
});

$this->assertEquals('Hello World', $factory->getFoo());
}

/**
* Get a database connection instance.
*
Expand Down