Skip to content

Commit

Permalink
Adds define() method to ModelFactory (#5897)
Browse files Browse the repository at this point in the history
* Adds `define()` method to `ModelFactory`

* Update CHANGELOG-3.1.md
  • Loading branch information
huangdijia authored Jul 3, 2023
1 parent 4cb1568 commit 9d788a0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
5 changes: 4 additions & 1 deletion src/Concerns/InteractsWithModelFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ trait InteractsWithModelFactory
{
protected ?ModelFactory $modelFactory = null;

protected string|array $factoryPath = BASE_PATH . '/database/factories';
/**
* @var string|string[]
*/
protected $factoryPath = BASE_PATH . '/database/factories';

protected function setUpInteractsWithModelFactory()
{
Expand Down
17 changes: 11 additions & 6 deletions src/ModelFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,27 @@ public static function create(Generator $faker)
return new static(new Factory($faker));
}

public function define(string $class, callable $attributes, string $name = 'default'): void
{
$this->factory->define(...func_get_args());
}

/**
* @param class-string<T> $model
* @param class-string<T> $class
* @return T
*/
public function factory(string $model, ...$arguments)
public function factory(string $class)
{
$factory = $this->factory;
$arguments = func_get_args();

if (isset($arguments[1]) && is_string($arguments[1])) {
return $factory->of($arguments[0], $arguments[1])->times($arguments[2] ?? null);
return $this->factory->of($arguments[0], $arguments[1])->times($arguments[2] ?? null);
}
if (isset($arguments[1])) {
return $factory->of($arguments[0])->times($arguments[1]);
return $this->factory->of($arguments[0])->times($arguments[1]);
}

return $factory->of($arguments[0]);
return $this->factory->of($arguments[0]);
}

public function load(string $path): void
Expand Down

0 comments on commit 9d788a0

Please sign in to comment.