-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathPersistentObjectFactory.php
More file actions
622 lines (509 loc) · 20.7 KB
/
PersistentObjectFactory.php
File metadata and controls
622 lines (509 loc) · 20.7 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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
<?php
/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <kevinbond@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zenstruck\Foundry\Persistence;
use Doctrine\Persistence\ObjectRepository;
use Symfony\Component\VarExporter\Exception\LogicException as VarExportLogicException;
use Zenstruck\Foundry\Configuration;
use Zenstruck\Foundry\Exception\FoundryNotBooted;
use Zenstruck\Foundry\Exception\PersistenceDisabled;
use Zenstruck\Foundry\Exception\PersistenceNotAvailable;
use Zenstruck\Foundry\Factory;
use Zenstruck\Foundry\FactoryCollection;
use Zenstruck\Foundry\Object\Hydrator;
use Zenstruck\Foundry\ObjectFactory;
use Zenstruck\Foundry\Persistence\Event\AfterPersist;
use Zenstruck\Foundry\Persistence\Exception\NotEnoughObjects;
use Zenstruck\Foundry\Persistence\Exception\RefreshObjectFailed;
use Zenstruck\Foundry\Persistence\Relationship\ManyToOneRelationship;
use Zenstruck\Foundry\Persistence\Relationship\OneToManyRelationship;
use Zenstruck\Foundry\Persistence\Relationship\OneToOneRelationship;
use function Zenstruck\Foundry\force;
use function Zenstruck\Foundry\get;
use function Zenstruck\Foundry\set;
/**
* @author Kevin Bond <kevinbond@gmail.com>
*
* @template T of object
* @extends ObjectFactory<T>
*
* @phpstan-import-type Parameters from Factory
*/
abstract class PersistentObjectFactory extends ObjectFactory
{
public const PRIORITY_SCHEDULE_FOR_INSERT = -10;
private PersistMode $persist = PersistMode::PERSIST;
/** @phpstan-var array<int, list<callable(T, Parameters, static):void|callable(T, Parameters, static):bool>> */
private array $afterPersist = [];
/** @var list<callable(T):void> */
private array $inverseRelationshipCallbacks = [];
private bool $isRootFactory = true;
private ?bool $autorefreshEnabled = null;
/**
* @phpstan-param mixed|Parameters $criteriaOrId
*
* @return T
*
* @throws \RuntimeException If no object found
*/
public static function find(mixed $criteriaOrId): object
{
return static::repository()->findOrFail($criteriaOrId);
}
/**
* @phpstan-param Parameters $criteria
*
* @return T
*/
public static function findOrCreate(array $criteria): object
{
try {
$object = static::repository()->findOneBy($criteria);
} catch (PersistenceNotAvailable|PersistenceDisabled) {
$object = null;
}
return $object ?? static::createOne($criteria);
}
/**
* @phpstan-param Parameters $criteria
*
* @return T
*/
public static function randomOrCreate(array $criteria = []): object
{
try {
return static::repository()->random($criteria);
} catch (NotEnoughObjects|PersistenceNotAvailable|PersistenceDisabled) {
return static::createOne($criteria);
}
}
/**
* @param positive-int $count
* @phpstan-param Parameters $criteria
*
* @return non-empty-list<T>
*/
public static function randomSet(int $count, array $criteria = []): array
{
return static::repository()->randomSet($count, $criteria);
}
/**
* @param int<0, max> $min
* @param int<0, max> $max
* @phpstan-param Parameters $criteria
*
* @return list<T>
* @phpstan-return ($min is positive-int ? non-empty-list<T> : list<T>)
*/
public static function randomRange(int $min, int $max, array $criteria = []): array
{
return static::repository()->randomRange($min, $max, $criteria);
}
/**
* @param int<0, max> $min
* @param int<0, max> $max
* @phpstan-param Parameters $criteria
*
* @return list<T>
* @phpstan-return ($min is positive-int ? non-empty-list<T> : list<T>)
*/
public static function randomRangeOrCreate(int $min, int $max, array $criteria = []): array
{
$targetCount = \mt_rand($min, $max);
try {
return static::repository()->randomRange($min, $targetCount, $criteria);
} catch (NotEnoughObjects) {
$foundObjects = static::repository()->findBy($criteria);
} catch (PersistenceNotAvailable|PersistenceDisabled) {
$foundObjects = [];
}
$objectsToCreate = $targetCount - \count($foundObjects);
$newObjects = static::createMany($objectsToCreate, $criteria);
return [...$foundObjects, ...$newObjects];
}
/**
* @phpstan-param Parameters $criteria
*
* @return list<T>
*/
public static function findBy(array $criteria): array
{
return static::repository()->findBy($criteria);
}
/**
* @phpstan-param Parameters $criteria
*
* @return T
*/
public static function random(array $criteria = []): object
{
return static::repository()->random($criteria);
}
/**
* @return T
*
* @throws \RuntimeException If no objects exist
*/
public static function first(string $sortBy = 'id'): object
{
/** @var T $object */
$object = static::repository()->firstOrFail($sortBy);
return $object;
}
/**
* @return T
*
* @throws \RuntimeException If no objects exist
*/
public static function last(string $sortBy = 'id'): object
{
/** @var T $object */
$object = static::repository()->lastOrFail($sortBy);
return $object;
}
/**
* @return list<T>
*/
public static function all(): array
{
return static::repository()->findAll();
}
/**
* @return RepositoryDecorator<T,ObjectRepository<T>>
*/
public static function repository(): ObjectRepository
{
Configuration::instance()->assertPersistenceEnabled();
return new RepositoryDecorator(static::class(), Configuration::instance()->isInMemoryEnabled()); // @phpstan-ignore return.type
}
final public static function assert(): RepositoryAssertions
{
return static::repository()->assert();
}
/**
* @phpstan-param Parameters $criteria
*/
final public static function count(array $criteria = []): int
{
return static::repository()->count($criteria);
}
final public static function truncate(): void
{
static::repository()->truncate();
}
/**
* @return T
*/
public function create(callable|array $attributes = []): object
{
$configuration = Configuration::instance();
if ($configuration->inADataProvider()
&& (\PHP_VERSION_ID >= 80400 || $this instanceof PersistentProxyObjectFactory)
&& ($this->isPersisting() || $configuration->isInMemoryEnabled())
) {
return ProxyGenerator::wrapFactory($this->with($attributes));
}
$object = parent::create($attributes);
$this->throwIfCannotCreateObject();
if (PersistMode::PERSIST !== $this->persistMode()) {
return $object;
}
if ($configuration->flushOnce && !$this->isRootFactory) {
return $object;
}
if (!$configuration->isPersistenceAvailable()) {
throw new \LogicException('Persistence cannot be used in unit tests.');
}
$configuration->persistence()->save($object);
return $object;
}
final public function andPersist(): static
{
$clone = clone $this;
$clone->persist = PersistMode::PERSIST;
return $clone;
}
final public function withoutPersisting(): static
{
$clone = clone $this;
$clone->persist = PersistMode::WITHOUT_PERSISTING;
return $clone;
}
final public function withAutorefresh(): static
{
if (\PHP_VERSION_ID < 80400) {
throw new \LogicException('Auto-refresh requires PHP 8.4 or higher.');
}
$clone = clone $this;
$clone->autorefreshEnabled = true;
return $clone;
}
final public function withoutAutorefresh(): static
{
if (\PHP_VERSION_ID < 80400) {
throw new \LogicException('Auto-refresh requires PHP 8.4 or higher.');
}
$clone = clone $this;
$clone->autorefreshEnabled = false;
return $clone;
}
/**
* @internal
*/
public function withPersistMode(PersistMode $persistMode): static
{
$clone = clone $this;
$clone->persist = $persistMode;
return $clone;
}
/**
* @phpstan-param callable(T, Parameters, static):void|callable(T, Parameters, static):bool $callback return value tells if a flush should be performed after the callback
*/
final public function afterPersist(callable $callback, int $priority = 0): static
{
$clone = clone $this;
$afterPersist = $clone->afterPersist;
$afterPersist[$priority] ??= [];
$afterPersist[$priority][] = $callback;
\krsort($afterPersist);
$clone->afterPersist = $afterPersist;
return $clone;
}
/**
* @internal
*/
public function persistMode(): PersistMode
{
return $this->isPersistenceEnabled() && !$this->isInMemoryEnabled() ? $this->persist : PersistMode::WITHOUT_PERSISTING;
}
final public function isPersisting(): bool
{
return $this->persistMode()->isPersisting();
}
/**
* @internal
*/
public function notRootFactory(): static
{
$clone = clone $this;
$clone->isRootFactory = false;
return $clone;
}
/**
* @internal
*/
public function isAutorefreshEnabled(): bool
{
return $this->autorefreshEnabled ??= Configuration::autoRefreshWithLazyObjectsIsEnabled();
}
protected function normalizeParameter(string $field, mixed $value): mixed
{
if (!Configuration::instance()->isPersistenceAvailable()) {
return ProxyGenerator::unwrap(parent::normalizeParameter($field, $value));
}
if ($value instanceof self) {
$value = $value
->withPersistMode($this->persist)
->notRootFactory();
$pm = Configuration::instance()->persistence();
$relationshipMetadata = $pm->bidirectionalRelationshipMetadata(static::class(), $value::class(), $field);
// handle inverse OneToOne
if ($relationshipMetadata instanceof OneToOneRelationship && !$relationshipMetadata->isOwning) {
$inverseField = $relationshipMetadata->inverseField();
$value = $value
->reuse(...$this->reusedObjects(), ...$value->reusedObjects())
->withPersistMode(
$this->isPersisting() ? PersistMode::NO_PERSIST_BUT_SCHEDULE_FOR_INSERT : PersistMode::WITHOUT_PERSISTING
)
;
if (($fieldType = (new \ReflectionClass(static::class()))->getProperty($field)->getType())?->allowsNull()) {
$this->inverseRelationshipCallbacks[] = static function(object $object) use ($value, $inverseField, $field) {
$inverseObject = $value->create([$inverseField => $object]);
set($object, $field, ProxyGenerator::unwrap($inverseObject, withAutoRefresh: false));
};
// we're using "force" here to avoid a potential type check in a setter
return force(null);
} elseif (($inverseFieldType = (new \ReflectionClass($value::class()))->getProperty($inverseField)->getType())?->allowsNull()) {
$inverseObject = ProxyGenerator::unwrap(
// we're using "force" here to avoid a potential type check in a setter
$value->create([$inverseField => force(null)]),
withAutoRefresh: false
);
$this->inverseRelationshipCallbacks[] = static function(object $object) use ($inverseObject, $inverseField) {
set($inverseObject, $inverseField, $object);
};
return $inverseObject;
} elseif (null === $fieldType || null === $inverseFieldType) {
throw new \InvalidArgumentException(\sprintf("Cannot handle inverse OneToOne relationship: cannot determine types of \"%s::\${$field}\" and \"%s::\${$inverseField}\", please and type to the properties.", static::class(), $value::class()));
}
throw new \InvalidArgumentException(\sprintf("Cannot handle inverse OneToOne relationship: both \"%s::\${$field}\" and \"%s::\${$inverseField}\" are not nullable, which will result in a circular dependency.", static::class(), $value::class()));
}
}
return ProxyGenerator::unwrap(parent::normalizeParameter($field, $value), withAutoRefresh: false);
}
protected function normalizeCollection(string $field, FactoryCollection $collection): array
{
if (!Configuration::instance()->isPersistenceAvailable() || !$collection->factory instanceof self) {
return parent::normalizeCollection($field, $collection);
}
$pm = Configuration::instance()->persistence();
$inverseRelationshipMetadata = $pm->bidirectionalRelationshipMetadata(static::class(), $collection->factory::class(), $field);
$collection = $collection->notRootFactory();
if ($inverseRelationshipMetadata instanceof OneToManyRelationship) {
$this->inverseRelationshipCallbacks[] = function(object $object) use ($collection, $inverseRelationshipMetadata, $field) {
$inverseField = $inverseRelationshipMetadata->inverseField();
$inverseObjects = $collection
->reuse(...$this->reusedObjects())
->withPersistMode($this->isPersisting() ? PersistMode::NO_PERSIST_BUT_SCHEDULE_FOR_INSERT : PersistMode::WITHOUT_PERSISTING)
->create([$inverseField => $object]);
$inverseObjects = ProxyGenerator::unwrap($inverseObjects, withAutoRefresh: false);
// if the collection is indexed by a field, index the array
if ($inverseRelationshipMetadata->collectionIndexedBy) {
$inverseObjects = \array_combine(
\array_map(static fn($o) => get($o, $inverseRelationshipMetadata->collectionIndexedBy), $inverseObjects),
\array_values($inverseObjects)
);
// using forceSet to prevent usage of PropertyAccessor,
// which will potentially call adders and lose index information
Hydrator::forceSet($object, $field, $inverseObjects);
} else {
$this->hydrator()->setProperty($object, $field, $inverseObjects);
}
};
// creation delegated to tempAfterInstantiate hook - return an empty array here
return [];
}
return parent::normalizeCollection($field, $collection);
}
/**
* This method will try to find entities in the database if they are detached.
*
* @internal
*/
protected function normalizeObject(string $field, object $object): object
{
$configuration = Configuration::instance();
$object = ProxyGenerator::unwrap($object, withAutoRefresh: false);
if (!$configuration->isPersistenceAvailable()) {
return $object;
}
$persistenceManager = $configuration->persistence();
if (!$persistenceManager->hasPersistenceFor($object)) {
return $object;
}
$inverseRelationship = $persistenceManager->bidirectionalRelationshipMetadata(static::class(), $object::class, $field);
if ($inverseRelationship instanceof OneToOneRelationship) {
$this->inverseRelationshipCallbacks[] = function(object $newObject) use ($object, $inverseRelationship) {
$this->hydrator()->setProperty($object, $inverseRelationship->inverseField(), $newObject, catchErrors: true);
};
}
if ($inverseRelationship instanceof ManyToOneRelationship) {
$this->inverseRelationshipCallbacks[] = function (object $newObject) use ($object, $inverseRelationship) {
$this->hydrator()->add($object, $inverseRelationship->inverseField(), $newObject);
};
}
if (
!$this->isPersisting()
) {
return $object;
}
if (!$persistenceManager->isPersisted($object)) {
$persistenceManager->scheduleForInsert($object);
return $object;
}
try {
return $configuration->persistence()->refresh($object);
} catch (RefreshObjectFailed|VarExportLogicException) { // @phpstan-ignore catch.neverThrown (thrown by var exporter)
return $object;
}
}
/**
* @internal
*/
final protected function initializeInternal(): static
{
// Schedule any new object for insert right after instantiation
$factory = parent::initializeInternal()
->afterInstantiate(
static function(object $object, array $parameters, PersistentObjectFactory $factoryUsed): void {
if (!$factoryUsed->isPersisting()) {
return;
}
$afterPersistCallbacks = [];
foreach (\array_merge(...$factoryUsed->afterPersist) as $afterPersist) {
$afterPersistCallbacks[] = static function() use ($object, $afterPersist, $parameters, $factoryUsed): bool {
// this condition is needed to avoid BC breaks: only avoid flush if the callback explicitly returns false
return !(false === $afterPersist($object, $parameters, $factoryUsed));
};
}
Configuration::instance()->persistence()->scheduleForInsert($object, $afterPersistCallbacks);
},
self::PRIORITY_SCHEDULE_FOR_INSERT
)
// Always register the callback that executes inverse relationship callbacks.
// This is needed even when Foundry is not booted (e.g., when factories are created in data providers
// without the PHPUnit extension), because the callbacks are populated later during create().
->afterInstantiate(
static function(object $object, array $parameters, self $factoryUsed): void {
$tempAfterInstantiateCallbacks = $factoryUsed->inverseRelationshipCallbacks;
$factoryUsed->inverseRelationshipCallbacks = [];
foreach ($tempAfterInstantiateCallbacks as $tempAfterInstantiateCallback) {
$tempAfterInstantiateCallback($object);
}
},
priority: 1000
)
;
if (!Configuration::isBooted() || !Configuration::instance()->hasEventDispatcher()) {
return $factory;
}
return $factory->afterPersist(
static function(object $object, array $parameters, self $factoryUsed): bool {
Configuration::instance()->eventDispatcher()->dispatch(
new AfterPersist($object, $parameters, $factoryUsed)
);
return false; // don't perform a flush after the hook
}
);
}
private function throwIfCannotCreateObject(): void
{
$configuration = Configuration::instance();
/**
* "false === $configuration->inADataProvider()" would also mean that the PHPUnit extension is NOT used
* so a `FoundryNotBooted` exception would be thrown if we actually are in a data provider.
*/
if (!$configuration->inADataProvider()) {
return;
}
if (
$this instanceof PersistentProxyObjectFactory
|| !$this->isPersisting()
) {
return;
}
throw new \LogicException(\sprintf('Cannot create object in a data provider for non-proxy factories. Transform your factory into a "%s", or call "create()" method in the test. See https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#phpunit-data-providers', PersistentProxyObjectFactory::class));
}
private function isPersistenceEnabled(): bool
{
try {
return Configuration::instance()->isPersistenceEnabled();
} catch (FoundryNotBooted) {
return false;
}
}
private function isInMemoryEnabled(): bool
{
try {
return Configuration::instance()->isInMemoryEnabled();
} catch (FoundryNotBooted) {
return false;
}
}
}