You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.6 KiB

2 years ago
  1. <?php
  2. namespace Database\Factories;
  3. use Illuminate\Support\Str;
  4. trait BaseFactory
  5. {
  6. public function smash($key)
  7. {
  8. $field = explode(':', $key)[0];
  9. $methodName = '__' . explode(':', $key)[1];
  10. $param = explode(':', $key)[2] ?? [];
  11. $param = is_array($param) ? $param : [$param];
  12. $param = array_merge( [$field], is_array($param) ? $param : [$param]);
  13. return $this->state(function (array $attributes) use ($field, $methodName, $param) {
  14. $states[$field] = call_user_func_array([static::class, $methodName], $param);
  15. return $states;
  16. });
  17. }
  18. protected function __null($field = null)
  19. {
  20. return null;
  21. }
  22. protected function __string($field = null, $length = 16): string
  23. {
  24. return Str::random($length);
  25. }
  26. protected function __gtString($field = null, $min = 256)
  27. {
  28. return $this->__string($field, rand($min + 1, $min + 1000));
  29. }
  30. protected function __ltString($field = null, $max = 3)
  31. {
  32. return $this->__string($field, $max - 1);
  33. }
  34. protected function __unique($field)
  35. {
  36. return $this->model::factory()->createQuietly()->{$field};
  37. }
  38. protected function __numeric($field)
  39. {
  40. return rand(100, 200);
  41. }
  42. protected function __lt($field = null, $max = 4)
  43. {
  44. return rand($max - 100, $max - 1);
  45. }
  46. protected function __gt($field = null, $min = 4)
  47. {
  48. return rand($min + 1, $min + 100);
  49. }
  50. public function withDependency()
  51. {
  52. return $this->state(function (array $attributes) {
  53. return $this->dependencyProvider();
  54. });
  55. }
  56. }