1 | <?php |
||
2 | |||
3 | namespace Spatie\Enum\Laravel\Faker; |
||
4 | |||
5 | use Faker\Generator as FakerGenerator; |
||
6 | use Faker\Provider\Base; |
||
7 | use InvalidArgumentException; |
||
8 | use Spatie\Enum\Enum; |
||
9 | |||
10 | class FakerEnumProvider extends Base |
||
11 | { |
||
12 | public static function register(): void |
||
13 | { |
||
14 | /** @var FakerGenerator $faker */ |
||
15 | $faker = app(FakerGenerator::class); |
||
16 | |||
17 | $providers = array_map('get_class', $faker->getProviders()); |
||
18 | |||
19 | if (in_array(static::class, $providers)) { |
||
20 | return; |
||
21 | } |
||
22 | |||
23 | $faker->addProvider(new static($faker)); |
||
24 | } |
||
25 | |||
26 | /** |
||
27 | * A random instance of the enum you pass in. |
||
28 | * |
||
29 | * @param string $enum |
||
30 | * |
||
31 | * @return Enum |
||
32 | */ |
||
33 | public function randomEnum(string $enum): Enum |
||
34 | { |
||
35 | if (! is_subclass_of($enum, Enum::class)) { |
||
36 | throw new InvalidArgumentException(sprintf( |
||
37 | 'You have to pass the FQCN of a "%s" class but you passed "%s".', |
||
38 | Enum::class, |
||
39 | $enum |
||
40 | )); |
||
41 | } |
||
42 | |||
43 | return $enum::make(static::randomElement(array_keys($enum::toArray()))); |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * A random value of the enum you pass in. |
||
48 | * |
||
49 | * @param string $enum |
||
50 | * |
||
51 | * @return string|int |
||
52 | */ |
||
53 | public function randomEnumValue(string $enum) |
||
54 | { |
||
55 | if (! is_subclass_of($enum, Enum::class)) { |
||
56 | throw new InvalidArgumentException(sprintf( |
||
57 | 'You have to pass the FQCN of a "%s" class but you passed "%s".', |
||
58 | Enum::class, |
||
59 | $enum |
||
60 | )); |
||
61 | } |
||
62 | |||
63 | return static::randomElement(array_keys($enum::toArray())); |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * A random label of the enum you pass in. |
||
68 | * |
||
69 | * @param string $enum |
||
70 | * |
||
71 | * @return string |
||
72 | */ |
||
73 | public function randomEnumLabel(string $enum): string |
||
74 | { |
||
75 | if (! is_subclass_of($enum, Enum::class)) { |
||
76 | throw new InvalidArgumentException(sprintf( |
||
77 | 'You have to pass the FQCN of a "%s" class but you passed "%s".', |
||
78 | Enum::class, |
||
79 | $enum |
||
80 | )); |
||
81 | } |
||
82 | |||
83 | return static::randomElement(array_values($enum::toArray())); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
84 | } |
||
85 | } |
||
86 |