Skip to content

Commit

Permalink
relationships: fix cascade removal of parent in oneHasMany [closes #235]
Browse files Browse the repository at this point in the history
  • Loading branch information
hrach committed Jan 12, 2020
1 parent 8584ef8 commit cd6d286
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
13 changes: 10 additions & 3 deletions src/Repository/RemovalHelper.php
Expand Up @@ -35,7 +35,7 @@ public static function getCascadeQueueAndSetNulls(IEntity $entity, IModel $model

list ($pre, $post, $nulls) = static::getRelationships($entity);
$prePersist = [];
static::setNulls($entity, $nulls, $model, $prePersist);
static::setNulls($entity, $nulls, $model, $prePersist, $queueRemove);

if (!$withCascade) {
$queueRemove[$entityHash] = $entity;
Expand All @@ -45,6 +45,7 @@ public static function getCascadeQueueAndSetNulls(IEntity $entity, IModel $model
foreach ($prePersist as $value) {
$queuePersist[spl_object_hash($value)] = $value;
}
$queueRemove[$entityHash] = true;
foreach ($pre as $value) {
if ($value instanceof IEntity) {
static::getCascadeQueueAndSetNulls($value, $model, true, $queuePersist, $queueRemove);
Expand All @@ -55,6 +56,7 @@ public static function getCascadeQueueAndSetNulls(IEntity $entity, IModel $model
$queuePersist[spl_object_hash($value)] = $value;
}
}
unset($queueRemove[$entityHash]);
$queueRemove[$entityHash] = $entity;
unset($queuePersist[$entityHash]);
foreach ($post as $value) {
Expand Down Expand Up @@ -115,7 +117,7 @@ public static function getRelationships(IEntity $entity): array
/**
* @param PropertyMetadata[] $metadata
*/
private static function setNulls(IEntity $entity, array $metadata, IModel $model, array & $pre)
private static function setNulls(IEntity $entity, array $metadata, IModel $model, array & $pre, array & $queueRemove)
{
foreach ($metadata as $propertyMeta) {
assert($propertyMeta->relationship !== null);
Expand Down Expand Up @@ -147,7 +149,12 @@ private static function setNulls(IEntity $entity, array $metadata, IModel $model
$property = $entity->getProperty($name);
assert($property instanceof HasOne);
if ($reverseProperty !== null && $entity->hasValue($name)) {
$pre[] = $entity->getValue($name)->getProperty($reverseProperty->name);
$reverseEntity = $entity->getValue($name);
if (isset($queueRemove[spl_object_hash($reverseEntity)])) {
// reverse side is also being removed, do not set null to this relationship
continue;
}
$pre[] = $reverseEntity->getProperty($reverseProperty->name);
}
$property->set(null, true);

Expand Down
2 changes: 1 addition & 1 deletion tests/inc/model/contents/Comment.php
Expand Up @@ -11,7 +11,7 @@

/**
* @property-read string $type {default comment}
* @property Thread|null $thread {m:1 Thread::$comments}
* @property Thread $thread {m:1 Thread::$comments}
* @property \DateTimeImmutable $repliedAt
*/
class Comment extends ThreadCommentCommon
Expand Down

0 comments on commit cd6d286

Please sign in to comment.