namespace Drupal\Core\TempStore;
+use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Core\Session\AccountProxyInterface;
* \Drupal\Core\TempStore\SharedTempStore.
*/
class PrivateTempStore {
+ use DependencySerializationTrait;
/**
* The key/value storage object used for this data.
* 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);
* 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();
+ }
}
}