Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: flush only once per calls to Factory::create() in userland #836

Draft
wants to merge 5 commits into
base: 2.3.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ protected function normalizeParameter(string $field, mixed $value): mixed
);
}

return \is_object($value) ? $this->normalizeObject($value) : $value;
return \is_object($value) ? $this->normalizeObject($field, $value) : $value;
}

/**
Expand All @@ -253,7 +253,7 @@ protected function normalizeCollection(string $field, FactoryCollection $collect
/**
* @internal
*/
protected function normalizeObject(object $object): object
protected function normalizeObject(string $field, object $object): object
{
return $object;
}
Expand Down
16 changes: 6 additions & 10 deletions src/ORM/OrmV2PersistenceStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,13 @@ public function inversedRelationshipMetadata(string $parent, string $child, stri
throw new \LogicException("Cannot find correct association named \"{$field}\" between classes [parent: \"{$parent}\", child: \"{$child}\"]");
}

// exclude "owning" side of the association (owning OneToOne or ManyToOne)
if (!\in_array(
$inversedAssociation['type'],
[ClassMetadataInfo::ONE_TO_MANY, ClassMetadataInfo::ONE_TO_ONE],
true
)
|| !isset($inversedAssociation['mappedBy'])
) {
$inverseField = $inversedAssociation['isOwningSide'] ? $inversedAssociation['inversedBy'] ?? null : $inversedAssociation['mappedBy'] ?? null;

if (null === $inverseField) {
return null;
}

$association = $metadata->getAssociationMapping($inversedAssociation['mappedBy']);
$association = $metadata->getAssociationMapping($inverseField);

// only keep *ToOne associations
if (!$metadata->isSingleValuedAssociation($association['fieldName'])) {
Expand All @@ -66,7 +61,8 @@ public function inversedRelationshipMetadata(string $parent, string $child, stri
return new InverseRelationshipMetadata(
inverseField: $association['fieldName'],
isCollection: $inversedAssociationMetadata->isCollectionValuedAssociation($inversedAssociation['fieldName']),
collectionIndexedBy: $inversedAssociation['indexBy'] ?? null
collectionIndexedBy: ($inversedAssociationMetadata->isCollectionValuedAssociation($inversedAssociation['fieldName']) && isset($inversedAssociation['indexBy'])) ? $inversedAssociation['indexBy'] : null,
isOwningSide: !$inversedAssociation['isOwningSide']
);
}

Expand Down
10 changes: 6 additions & 4 deletions src/ORM/OrmV3PersistenceStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,13 @@ public function inversedRelationshipMetadata(string $parent, string $child, stri
throw new \LogicException("Cannot find correct association named \"{$field}\" between classes [parent: \"{$parent}\", child: \"{$child}\"]");
}

// exclude "owning" side of the association (owning OneToOne or ManyToOne)
if (!$inversedAssociation instanceof InverseSideMapping) {
$inverseField = $inversedAssociation->isOwningSide() ? $inversedAssociation->inversedBy : $inversedAssociation->mappedBy;

if (null === $inverseField) {
return null;
}

$association = $metadata->getAssociationMapping($inversedAssociation->mappedBy);
$association = $metadata->getAssociationMapping($inverseField);

// only keep *ToOne associations
if (!$metadata->isSingleValuedAssociation($association->fieldName)) {
Expand All @@ -56,7 +57,8 @@ public function inversedRelationshipMetadata(string $parent, string $child, stri
return new InverseRelationshipMetadata(
inverseField: $association->fieldName,
isCollection: $inversedAssociation instanceof ToManyAssociationMapping,
collectionIndexedBy: $inversedAssociation->isIndexed() ? $inversedAssociation->indexBy() : null
collectionIndexedBy: $inversedAssociation instanceof ToManyAssociationMapping && $inversedAssociation->isIndexed() ? $inversedAssociation->indexBy() : null,
isOwningSide: !$inversedAssociation->isOwningSide()
);
}

Expand Down
6 changes: 6 additions & 0 deletions src/Persistence/InverseRelationshipMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ public function __construct(
public readonly string $inverseField,
public readonly bool $isCollection,
public readonly ?string $collectionIndexedBy,
public readonly bool $isOwningSide,
) {
}

public function isInverseOneToOne(): bool
{
return !$this->isCollection && $this->isOwningSide;
}
}
106 changes: 80 additions & 26 deletions src/Persistence/PersistenceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,14 @@ final class PersistenceManager
private bool $flush = true;
private bool $persist = true;

/** @var list<object> */
private array $objectsToPersist = [];

/** @var list<callable():void> */
private array $afterPersistCallbacks = [];

private bool $transactinStarted = false;

/**
* @param iterable<PersistenceStrategy> $strategies
*/
Expand Down Expand Up @@ -75,18 +80,48 @@ public function save(object $object): object
$om->persist($object);
$this->flush($om);

if ($this->afterPersistCallbacks) {
$afterPersistCallbacks = $this->afterPersistCallbacks;
$this->afterPersistCallbacks = [];
return $object;
}

foreach ($afterPersistCallbacks as $afterPersistCallback) {
$afterPersistCallback();
/**
* We're using so-called "transactions" to group multiple persist/flush operations
* This prevents such code to persist the whole batch of objects in the normalization phase:
* ```php
* SomeFactory::createOne(['item' => lazy(fn() => OtherFactory::createOne())]);
* ```
*/
public function startTransaction(): void
{
$this->transactinStarted = true;
}

public function isTransactionStarted(): bool
{
return $this->transactinStarted;
}

public function commit(): void
{
$objectManagers = [];

$objectsToPersist = $this->objectsToPersist;
$this->objectsToPersist = [];
$this->transactinStarted = false;

foreach ($objectsToPersist as $object) {
$om = $this->strategyFor($object::class)->objectManagerFor($object::class);
$om->persist($object);

if (!\in_array($om, $objectManagers, true)) {
$objectManagers[] = $om;
}
}

$this->save($object);
foreach ($objectManagers as $om) {
$this->flush($om);
}

return $object;
$this->callPostPersistCallbacks();
}

/**
Expand All @@ -103,23 +138,19 @@ public function scheduleForInsert(object $object, array $afterPersistCallbacks =
$object = unproxy($object);
}

$om = $this->strategyFor($object::class)->objectManagerFor($object::class);
$om->persist($object);

$this->afterPersistCallbacks = [...$this->afterPersistCallbacks, ...$afterPersistCallbacks];

return $object;
}
// if (0 === \count($this->objectsToPersist)) {
// throw new \LogicException('No transaction started yet.');
// }

public function forget(object $object): void
{
if ($this->isPersisted($object)) {
throw new \LogicException('Cannot forget an object already persisted.');
}
// $transactionCount = \count($this->objectsToPersist) - 1;
$this->objectsToPersist[] = $object;

$om = $this->strategyFor($object::class)->objectManagerFor($object::class);
$this->afterPersistCallbacks = [
...$this->afterPersistCallbacks,
...$afterPersistCallbacks,
];

$om->detach($object);
return $object;
}

/**
Expand All @@ -137,11 +168,9 @@ public function flushAfter(callable $callback): mixed

$this->flush = true;

foreach ($this->strategies as $strategy) {
foreach ($strategy->objectManagers() as $om) {
$this->flush($om);
}
}
$this->flushAllStrategies();

$this->callPostPersistCallbacks();

return $result;
}
Expand Down Expand Up @@ -372,6 +401,31 @@ public static function isOrmOnly(): bool
})();
}

private function flushAllStrategies(): void
{
foreach ($this->strategies as $strategy) {
foreach ($strategy->objectManagers() as $om) {
$this->flush($om);
}
}
}

private function callPostPersistCallbacks(): void
{
if (!$this->flush || [] === $this->afterPersistCallbacks) {
return;
}

$afterPersistCallbacks = $this->afterPersistCallbacks;
$this->afterPersistCallbacks = [];

foreach ($afterPersistCallbacks as $afterPersistCallback) {
$afterPersistCallback();
}

$this->flushAllStrategies();
}

/**
* @param class-string $class
*
Expand Down
Loading
Loading