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 committed Jul 3, 2023
1 parent 030405b commit 47a30da
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG-3.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
- [#5815](https://github.com/hyperf/hyperf/pull/5815) Added alias as `mysql` for `pdo` in `hyperf/db`.
- [#5849](https://github.com/hyperf/hyperf/pull/5849) Support for insert update and select using enums.
- [#5855](https://github.com/hyperf/hyperf/pull/5855) Added `hyperf/closure-command` component.
- [#5894](https://github.com/hyperf/hyperf/pull/5894) Added `model-factory` support for `hyperf/testing`.
- [#5894](https://github.com/hyperf/hyperf/pull/5894) [#5897](https://github.com/hyperf/hyperf/pull/5897) Added `model-factory` support for `hyperf/testing`.

## Optimized

Expand Down
5 changes: 4 additions & 1 deletion src/testing/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/testing/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 47a30da

Please sign in to comment.