From d2ab9b84338300321de2d1089c2293874af4aada Mon Sep 17 00:00:00 2001
From: Nathaniel Catchpole <catch@35733.no-reply.drupal.org>
Date: Thu, 28 Jul 2016 13:47:58 +0100
Subject: [PATCH] Issue #2772979 by hchonov: Enforcing a cloned entity
 translation to be new propagates to the original entity

---
 .../Drupal/Core/Entity/ContentEntityBase.php  |  5 ++++
 .../Core/Entity/ContentEntityCloneTest.php    | 27 +++++++++++++++++++
 2 files changed, 32 insertions(+)

diff --git a/core/lib/Drupal/Core/Entity/ContentEntityBase.php b/core/lib/Drupal/Core/Entity/ContentEntityBase.php
index b5fccbd36940..7c0a4581de4b 100644
--- a/core/lib/Drupal/Core/Entity/ContentEntityBase.php
+++ b/core/lib/Drupal/Core/Entity/ContentEntityBase.php
@@ -1032,6 +1032,11 @@ public function __clone() {
       $this->clearTranslationCache();
       $translations = $this->translations;
       $this->translations = &$translations;
+
+      // Ensure the enforceIsNew property is actually cloned by overwriting the
+      // original reference with one pointing to a copy of it.
+      $enforce_is_new = $this->enforceIsNew;
+      $this->enforceIsNew = &$enforce_is_new;
     }
   }
 
diff --git a/core/tests/Drupal/KernelTests/Core/Entity/ContentEntityCloneTest.php b/core/tests/Drupal/KernelTests/Core/Entity/ContentEntityCloneTest.php
index 2a05b948fb4d..cca7eb129101 100644
--- a/core/tests/Drupal/KernelTests/Core/Entity/ContentEntityCloneTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Entity/ContentEntityCloneTest.php
@@ -62,4 +62,31 @@ public function testFieldEntityReferenceAfterClone() {
     }
   }
 
+  /**
+   * Tests that the flag for enforcing a new entity is not shared.
+   */
+  public function testEnforceIsNewOnClonedEntityTranslation() {
+    // Create a test entity.
+    $entity = EntityTestMul::create([
+      'name' => $this->randomString(),
+      'language' => 'en',
+    ]);
+    $entity->save();
+    $entity_translation = $entity->addTranslation('de');
+    $entity->save();
+
+    // The entity is not new anymore.
+    $this->assertFalse($entity_translation->isNew());
+
+    // The clone should not be new as well.
+    $clone = clone $entity_translation;
+    $this->assertFalse($clone->isNew());
+
+    // After enforcing the clone to be new only it should be flagged as new,
+    // but the original entity should not be flagged as new.
+    $clone->enforceIsNew();
+    $this->assertTrue($clone->isNew());
+    $this->assertFalse($entity_translation->isNew());
+  }
+
 }
-- 
GitLab