Pull merge.
[yaffs-website] / web / core / lib / Drupal / Core / TempStore / PrivateTempStore.php
index f9d10347050450e388e790deeb425aeaa01cfde3..606a0dc9e8db4952383cc2a6e892cc0c68854995 100644 (file)
@@ -2,6 +2,7 @@
 
 namespace Drupal\Core\TempStore;
 
+use Drupal\Core\DependencyInjection\DependencySerializationTrait;
 use Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface;
 use Drupal\Core\Lock\LockBackendInterface;
 use Drupal\Core\Session\AccountProxyInterface;
@@ -27,6 +28,7 @@ use Symfony\Component\HttpFoundation\RequestStack;
  * \Drupal\Core\TempStore\SharedTempStore.
  */
 class PrivateTempStore {
+  use DependencySerializationTrait;
 
   /**
    * The key/value storage object used for this data.
@@ -117,6 +119,19 @@ class PrivateTempStore {
    *   Thrown when a lock for the backend storage could not be acquired.
    */
   public function set($key, $value) {
+    // Ensure that an anonymous user has a session created for them, as
+    // otherwise subsequent page loads will not be able to retrieve their
+    // tempstore data.
+    if ($this->currentUser->isAnonymous()) {
+      // @todo when https://www.drupal.org/node/2865991 is resolved, use force
+      //   start session API rather than setting an arbitrary value directly.
+      $this->startSession();
+      $this->requestStack
+        ->getCurrentRequest()
+        ->getSession()
+        ->set('core.tempstore.private', TRUE);
+    }
+
     $key = $this->createkey($key);
     if (!$this->lockBackend->acquire($key)) {
       $this->lockBackend->wait($key);
@@ -207,7 +222,34 @@ class PrivateTempStore {
    *   The owner.
    */
   protected function getOwner() {
-    return $this->currentUser->id() ?: $this->requestStack->getCurrentRequest()->getSession()->getId();
+    $owner = $this->currentUser->id();
+    if ($this->currentUser->isAnonymous()) {
+      $this->startSession();
+      $owner = $this->requestStack->getCurrentRequest()->getSession()->getId();
+    }
+    return $owner;
+  }
+
+  /**
+   * Start session because it is required for a private temp store.
+   *
+   * Ensures that an anonymous user has a session created for them, as
+   * otherwise subsequent page loads will not be able to retrieve their
+   * tempstore data.
+   *
+   * @todo when https://www.drupal.org/node/2865991 is resolved, use force
+   * start session API.
+   */
+  protected function startSession() {
+    $has_session = $this->requestStack
+      ->getCurrentRequest()
+      ->hasSession();
+    if (!$has_session) {
+      /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */
+      $session = \Drupal::service('session');
+      $this->requestStack->getCurrentRequest()->setSession($session);
+      $session->start();
+    }
   }
 
 }