-
Notifications
You must be signed in to change notification settings - Fork 690
Expand file tree
/
Copy pathHasFieldFactory.php
More file actions
220 lines (187 loc) · 6.25 KB
/
HasFieldFactory.php
File metadata and controls
220 lines (187 loc) · 6.25 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
<?php
declare(strict_types=1);
namespace CraftCms\Cms\Database\Factories\Concerns;
use CraftCms\Cms\Database\Factories\ElementFactoryResult;
use CraftCms\Cms\Element\Element;
use CraftCms\Cms\Field\Models\Field;
use CraftCms\Cms\FieldLayout\LayoutElements\CustomField;
use CraftCms\Cms\FieldLayout\Models\FieldLayout;
use CraftCms\Cms\Support\Arr;
use CraftCms\Cms\Support\Facades\Elements;
use CraftCms\Cms\Support\Facades\EntryTypes;
use CraftCms\Cms\Support\Facades\Fields;
use CraftCms\Cms\Support\Str;
use CraftCms\Cms\Tests\TestClasses\Factory\FactoryFieldConfig;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Collection;
use Override;
/**
* Trait for element factories that need to create elements with custom fields.
*
* @mixin Factory
*/
trait HasFieldFactory
{
/** @var array<FactoryFieldConfig> */
protected array $fieldConfigs = [];
protected ?string $elementScenario = null;
/**
* Add a custom field to the element's field layout.
*/
public function withField(
string $handle,
string $type,
array $settings = [],
bool $required = false,
mixed $value = null,
): static {
$clone = clone $this;
$clone->fieldConfigs = [
...$this->fieldConfigs,
new FactoryFieldConfig(
handle: $handle,
type: $type,
settings: $settings,
required: $required,
value: $value,
),
];
return $clone;
}
/**
* Set the element scenario for validation.
*/
public function withScenario(string $scenario): static
{
$clone = clone $this;
$clone->elementScenario = $scenario;
return $clone;
}
/**
* Create the element with configured fields and return a result object.
*
* When `$save` is true (the default), the element is saved via `saveElement()`
* and re-queried from the database, ensuring field values are persisted.
*/
public function createElementWithFields(array $attributes = [], bool $save = true): ElementFactoryResult
{
$factory = $this->extractElementAttributes($attributes);
/** @var Collection<string, Field> $fields */
$fields = collect();
if (empty($factory->fieldConfigs)) {
return new ElementFactoryResult(
element: $factory->createElement($attributes),
fields: $fields,
);
}
foreach ($factory->fieldConfigs as $config) {
$field = Field::factory()->create([
'name' => Str::title($config->handle),
'handle' => $config->handle,
'type' => $config->type,
'settings' => $config->settings,
]);
$fields->put($config->handle, $field);
}
$fieldLayout = FieldLayout::create([
'type' => $factory->getElementClass(),
'config' => $factory->buildFieldLayoutConfig($fields),
]);
$model = $factory->create($attributes);
$factory->attachFieldLayoutToModel($model, $fieldLayout);
$factory->refreshFieldCaches();
$element = $factory->queryElement($model->id);
$element->setScenario($factory->elementScenario ?? Element::SCENARIO_DEFAULT);
$element->title = $element->title ?: 'Test entry';
foreach ($factory->fieldConfigs as $config) {
if ($config->value !== null) {
$element->setFieldValue($config->handle, $config->value);
}
}
if ($save) {
Elements::saveElement($element);
$element = $factory->queryElement($model->id);
}
return new ElementFactoryResult(
element: $element,
fields: $fields,
);
}
/**
* Build the field layout config for all fields.
*
* @param Collection<string, Field> $fields
*/
protected function buildFieldLayoutConfig(Collection $fields): array
{
$elements = [];
foreach ($this->fieldConfigs as $config) {
$field = $fields->get($config->handle);
if ($field) {
$elements[] = [
'uid' => Str::uuid()->toString(),
'type' => CustomField::class,
'fieldUid' => $field->uid,
'required' => $config->required,
];
}
}
return [
'tabs' => [
[
'uid' => Str::uuid()->toString(),
'name' => 'Content',
'elements' => $elements,
],
],
];
}
/**
* Refresh global caches after creating fields.
*/
protected function refreshFieldCaches(): void
{
EntryTypes::refreshEntryTypes();
Fields::refreshFields();
}
/**
* Extract title and slug from attributes and apply them as factory state.
*
* Returns a new factory instance with the state applied. The attributes
* array is modified by reference to remove the extracted keys.
*/
protected function extractElementAttributes(array &$attributes): static
{
$factory = clone $this;
if (Arr::has($attributes, 'title')) {
$factory = $factory->title(Arr::pull($attributes, 'title'));
}
if (Arr::has($attributes, 'slug')) {
return $factory->slug(Arr::pull($attributes, 'slug'));
}
return $factory;
}
/**
* @param array<string, mixed> $arguments
*/
#[Override]
protected function newInstance(array $arguments = []): static
{
$instance = parent::newInstance($arguments);
$instance->fieldConfigs = $this->fieldConfigs;
$instance->elementScenario = $this->elementScenario;
return $instance;
}
/**
* Get the element class for this factory.
*/
abstract protected function getElementClass(): string;
/**
* Attach the field layout to the created model.
*/
abstract protected function attachFieldLayoutToModel(mixed $model, FieldLayout $fieldLayout): void;
/**
* Query for the element by ID.
*/
abstract protected function queryElement(int $id): Element;
}