forked from leeovery/claude-laravel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataTestFactory.php
More file actions
107 lines (94 loc) · 2.45 KB
/
DataTestFactory.php
File metadata and controls
107 lines (94 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
declare(strict_types=1);
namespace Database\Factories\Data;
use App\Data\Data;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Collection;
/**
* Base factory class for all Data object test factories.
*
* Provides:
* - Definition pattern via abstract definition() method
* - Factory creation: new()
* - Single instance: make()
* - Collections: collect()
* - State pattern: state()
*
* @template TData
*/
abstract class DataTestFactory
{
use WithFaker;
/**
* @var null|class-string<Data|TData>
*/
protected ?string $dataClassName = null;
private array $states = [];
/**
* Define the default state for the Data object.
*
* Return an array that will be passed to Data::from()
*/
abstract public function definition(): array;
/**
* Create a new factory instance.
*
* @return static
*/
public static function new()
{
return tap(new static, function ($factory) {
$factory->setUpFaker();
});
}
/**
* Set the Data class this factory creates.
*
* Called automatically by HasTestFactory trait.
*/
public function setDataClass(string $className): void
{
$this->dataClassName = $className;
}
/**
* Create a collection of Data objects.
*
* @param array $attributes Override attributes
* @param int|null $count Number of items to create
* @return Collection<int, TData>
*/
public function collect($attributes = [], ?int $count = 1): Collection
{
return $this->dataClassName::collect(
collect(range(1, $count))->map(fn () => $this->make($attributes))
);
}
/**
* Create a single Data object instance.
*
* @param array $attributes Override attributes
* @return TData
*/
public function make($attributes = [])
{
return $this->dataClassName::from(
array_replace(
array_replace($this->definition(), ...$this->states),
$attributes
)
);
}
/**
* Apply a state to the factory.
*
* States are merged with definition() before creating the Data object.
*
* @param callable|array $array State array or callable returning array
* @return static
*/
protected function state(callable|array $array): static
{
$this->states[] = value($array);
return $this;
}
}