ModelFactory.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Testing;
  12. use Faker\Generator;
  13. use Hyperf\Database\Model\Factory;
  14. /**
  15. * @template T
  16. */
  17. class ModelFactory
  18. {
  19. public function __construct(protected Factory $factory)
  20. {
  21. }
  22. public static function create(Generator $faker)
  23. {
  24. return new static(new Factory($faker));
  25. }
  26. public function define(string $class, callable $attributes, string $name = 'default'): void
  27. {
  28. $this->factory->define(...func_get_args());
  29. }
  30. /**
  31. * @param class-string<T> $class
  32. * @return T
  33. */
  34. public function factory(string $class)
  35. {
  36. $arguments = func_get_args();
  37. if (isset($arguments[1]) && is_string($arguments[1])) {
  38. return $this->factory->of($arguments[0], $arguments[1])->times($arguments[2] ?? null);
  39. }
  40. if (isset($arguments[1])) {
  41. return $this->factory->of($arguments[0])->times($arguments[1]);
  42. }
  43. return $this->factory->of($arguments[0]);
  44. }
  45. public function load(string $path): void
  46. {
  47. $this->factory->load($path);
  48. }
  49. }