generated from ergebnis/php-package-template
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
FixtureFactory.php
482 lines (405 loc) · 14 KB
/
FixtureFactory.php
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
<?php
declare(strict_types=1);
/**
* Copyright (c) 2020-2024 Andreas Möller
*
* For the full copyright and license information, please view
* the LICENSE.md file that was distributed with this source code.
*
* @see https://github.com/ergebnis/factory-bot
*/
namespace Ergebnis\FactoryBot;
use Doctrine\Common;
use Doctrine\Instantiator;
use Doctrine\ORM;
use Ergebnis\Classy;
use Faker\Generator;
final class FixtureFactory
{
private Instantiator\Instantiator $instantiator;
private FieldResolution\FieldValueResolution\FieldValueResolutionStrategy $fieldValueResolutionStrategy;
private FieldResolution\CountResolution\CountResolutionStrategy $countResolutionStrategy;
private bool $persistAfterCreate = false;
/**
* @var array<string, EntityDefinition>
*/
private array $entityDefinitions = [];
public function __construct(
private ORM\EntityManagerInterface $entityManager,
private Generator $faker,
) {
$this->instantiator = new Instantiator\Instantiator();
$this->fieldValueResolutionStrategy = new FieldResolution\FieldValueResolution\WithOrWithoutOptionalFieldValue();
$this->countResolutionStrategy = new FieldResolution\CountResolution\BetweenMinimumAndMaximumCount();
}
/**
* Creates a definition for populating an entity with fake data.
*
* @phpstan-param class-string<T> $className
*
* @phpstan-template T
*
* @psalm-param class-string<T> $className
*
* @psalm-template T
*
* @param array<string, \Closure|FieldDefinition\Resolvable|mixed> $fieldDefinitions
*
* @throws Exception\ClassMetadataNotFound
* @throws Exception\ClassNotFound
* @throws Exception\EntityDefinitionAlreadyRegistered
* @throws Exception\InvalidFieldNames
*/
public function define(
string $className,
array $fieldDefinitions = [],
?\Closure $afterCreate = null,
): void {
if (\array_key_exists($className, $this->entityDefinitions)) {
throw Exception\EntityDefinitionAlreadyRegistered::for($className);
}
if (!\class_exists($className, true)) {
throw Exception\ClassNotFound::name($className);
}
try {
$classMetadata = $this->entityManager->getClassMetadata($className);
} catch (ORM\Mapping\MappingException) {
throw Exception\ClassMetadataNotFound::for($className);
}
/** @var array<int, string> $allFieldNames */
$allFieldNames = \array_merge(
\array_keys($classMetadata->fieldMappings),
\array_keys($classMetadata->associationMappings),
\array_keys($classMetadata->embeddedClasses),
);
$fieldNames = \array_filter($allFieldNames, static function (string $fieldName): bool {
return !\str_contains($fieldName, '.');
});
/** @var array<int, string> $extraFieldNames */
$extraFieldNames = \array_diff(
\array_keys($fieldDefinitions),
$fieldNames,
);
if ([] !== $extraFieldNames) {
throw Exception\InvalidFieldNames::notFoundIn(
$classMetadata->getName(),
...$extraFieldNames,
);
}
$fieldDefinitions = self::normalizeFieldDefinitions($fieldDefinitions);
$defaultEntity = $this->instantiator->instantiate($className);
foreach ($fieldNames as $fieldName) {
if (\array_key_exists($fieldName, $fieldDefinitions)) {
continue;
}
/** @var mixed $defaultFieldValue */
$defaultFieldValue = $classMetadata->getFieldValue(
$defaultEntity,
$fieldName,
);
$fieldDefinitions[$fieldName] = FieldDefinition::value($defaultFieldValue);
}
if (null === $afterCreate) {
$afterCreate = static function (): void {
// nothing to do here
};
}
$this->entityDefinitions[$className] = EntityDefinition::create(
$classMetadata,
$fieldDefinitions,
$afterCreate,
);
}
/**
* Loads entity-definition providers from the specified directory.
*
* @throws Exception\InvalidDefinition
* @throws Exception\InvalidDirectory
*/
public function load(string $directory): void
{
if (!\is_dir($directory)) {
throw Exception\InvalidDirectory::notDirectory($directory);
}
foreach (Classy\Constructs::fromDirectory($directory) as $construct) {
/** @var class-string $className */
$className = $construct->name();
try {
$reflection = new \ReflectionClass($className);
} catch (\ReflectionException) {
throw Exception\InvalidDefinition::canNotBeAutoloaded($className);
}
if (!$reflection->implementsInterface(EntityDefinitionProvider::class)) {
continue;
}
if ($reflection->isAbstract()) {
continue;
}
if (!$reflection->isInstantiable()) {
throw Exception\InvalidDefinition::canNotBeInstantiated($className);
}
try {
/** @var EntityDefinitionProvider $provider */
$provider = $reflection->newInstance();
} catch (\Exception $exception) {
throw Exception\InvalidDefinition::throwsExceptionDuringInstantiation(
$className,
$exception,
);
}
$provider->accept($this);
}
}
public function register(EntityDefinitionProvider ...$providers): void
{
foreach ($providers as $provider) {
$provider->accept($this);
}
}
/**
* Creates a single entity with all of its dependencies.
*
* @phpstan-param class-string<T> $className
*
* @phpstan-return T
*
* @phpstan-template T
*
* @psalm-param class-string<T> $className
*
* @psalm-return T
*
* @psalm-template T
*
* @param array<string, \Closure|FieldDefinition\Resolvable|mixed> $fieldDefinitionOverrides
*
* @throws Exception\EntityDefinitionNotRegistered
* @throws Exception\InvalidFieldNames
*
* @return object
*/
public function createOne(
string $className,
array $fieldDefinitionOverrides = [],
) {
if (!\array_key_exists($className, $this->entityDefinitions)) {
throw Exception\EntityDefinitionNotRegistered::for($className);
}
/** @var EntityDefinition $entityDefinition */
$entityDefinition = $this->entityDefinitions[$className];
$extraFieldNames = \array_diff(
\array_keys($fieldDefinitionOverrides),
\array_keys($entityDefinition->fieldDefinitions()),
);
if ([] !== $extraFieldNames) {
throw Exception\InvalidFieldNames::notFoundIn(
$entityDefinition->classMetadata()->getName(),
...$extraFieldNames,
);
}
/** @var ORM\Mapping\ClassMetadata $classMetadata */
$classMetadata = $entityDefinition->classMetadata();
$entity = $this->instantiator->instantiate($className);
$fieldDefinitions = \array_merge(
$entityDefinition->fieldDefinitions(),
self::normalizeFieldDefinitions($fieldDefinitionOverrides),
);
$fieldValues = \array_map(function (FieldDefinition\Resolvable $fieldDefinition) {
return $this->fieldValueResolutionStrategy->resolveFieldValue(
$this->faker,
$this,
$fieldDefinition,
);
}, $fieldDefinitions);
foreach ($fieldValues as $fieldName => $fieldValue) {
$this->setField(
$entity,
$entityDefinition,
$fieldName,
$fieldValue,
);
}
$afterCreate = $entityDefinition->afterCreate();
$afterCreate(
$entity,
$fieldValues,
$this->faker,
);
if ($this->persistAfterCreate && false === $classMetadata->isEmbeddedClass) {
$this->entityManager->persist($entity);
}
return $entity;
}
/**
* Creates an array of entities with all of their dependencies.
*
* @phpstan-param class-string<T> $className
*
* @phpstan-return array<int, T>
*
* @phpstan-template T
*
* @psalm-param class-string<T> $className
*
* @psalm-return list<T>
*
* @psalm-template T
*
* @param array<string, \Closure|FieldDefinition\Resolvable|mixed> $fieldDefinitionOverrides
*
* @throws Exception\EntityDefinitionNotRegistered
*
* @return array<int, object>
*/
public function createMany(
string $className,
Count $count,
array $fieldDefinitionOverrides = [],
): array {
$resolved = $this->countResolutionStrategy->resolveCount(
$this->faker,
$count,
);
if (0 === $resolved) {
return [];
}
return \array_map(function () use ($className, $fieldDefinitionOverrides) {
return $this->createOne(
$className,
$fieldDefinitionOverrides,
);
}, \range(1, $resolved));
}
/**
* Returns a fixture factory that utilizes the WithOptionalStrategy.
*
* With this strategy
*
* - an optional reference is always resolved
* - references resolve to an array containing at least one reference
*/
public function withOptional(): self
{
$instance = clone $this;
$instance->fieldValueResolutionStrategy = new FieldResolution\FieldValueResolution\WithOptionalFieldValue();
$instance->countResolutionStrategy = new FieldResolution\CountResolution\BetweenMinimumAndMaximumGreaterThanZeroCount();
return $instance;
}
/**
* Returns a fixture factory that utilizes the WithoutOptionalStrategy.
*
* With this strategy
*
* - an optional reference is never resolved
* - references resolve to an array containing only the minimum number of references
*/
public function withoutOptional(): self
{
$instance = clone $this;
$instance->fieldValueResolutionStrategy = new FieldResolution\FieldValueResolution\WithoutOptionalFieldValue();
$instance->countResolutionStrategy = new FieldResolution\CountResolution\MinimumCount();
return $instance;
}
/**
* Returns a fixture factory that persists entities after creation.
*/
public function persisting(): self
{
$instance = clone $this;
$instance->persistAfterCreate = true;
return $instance;
}
/**
* @param array<string, \Closure|FieldDefinition\Resolvable|mixed> $fieldDefinitions
*
* @return array<string, FieldDefinition\Resolvable>
*/
private static function normalizeFieldDefinitions(array $fieldDefinitions): array
{
return \array_map(static function ($fieldDefinition): FieldDefinition\Resolvable {
if ($fieldDefinition instanceof FieldDefinition\Resolvable) {
return $fieldDefinition;
}
if ($fieldDefinition instanceof \Closure) {
return FieldDefinition::closure($fieldDefinition);
}
return FieldDefinition::value($fieldDefinition);
}, $fieldDefinitions);
}
private function setField(
object $entity,
EntityDefinition $entityDefinition,
string $fieldName,
mixed $fieldValue,
): void {
$classMetadata = $entityDefinition->classMetadata();
if ($classMetadata->isCollectionValuedAssociation($fieldName)) {
$classMetadata->setFieldValue(
$entity,
$fieldName,
self::collectionFrom($fieldValue),
);
return;
}
$classMetadata->setFieldValue(
$entity,
$fieldName,
$fieldValue,
);
if (!\is_object($fieldValue)) {
return;
}
if (!$classMetadata->isSingleValuedAssociation($fieldName)) {
return;
}
$this->updateCollectionSideOfAssociation(
$entity,
$classMetadata,
$fieldName,
$fieldValue,
);
}
private static function collectionFrom(mixed $value = []): Common\Collections\ArrayCollection
{
if (!\is_array($value)) {
return new Common\Collections\ArrayCollection();
}
return new Common\Collections\ArrayCollection($value);
}
private function updateCollectionSideOfAssociation(
object $entity,
ORM\Mapping\ClassMetadata $classMetadata,
string $fieldName,
object $fieldValue,
): void {
$inversedBy = $this->resolveInversedBy(
$classMetadata,
$fieldName,
);
if (!\is_string($inversedBy)) {
return;
}
$classMetadataOfFieldValue = $this->entityManager->getClassMetadata($fieldValue::class);
$collection = $classMetadataOfFieldValue->getFieldValue(
$fieldValue,
$inversedBy,
);
if (!$collection instanceof Common\Collections\Collection) {
return;
}
$collection->add($entity);
}
private function resolveInversedBy(
ORM\Mapping\ClassMetadata $classMetadata,
string $fieldName,
): ?string {
$association = $classMetadata->getAssociationMapping($fieldName);
if (\is_array($association)) {
return $association['inversedBy'];
}
if ($association instanceof ORM\Mapping\AssociationMapping) {
return $association->inversedBy;
}
throw new \RuntimeException('This should not happen');
}
}