Skip to content

Commit fbfc387

Browse files
committed
Issue #3024452 by kfritsche, hchonov, alexpott: DatabaseStorageExpirable:setWithExpireIfNotExists is not respecting expired
(cherry picked from commit 62d162f)
1 parent 0692cf5 commit fbfc387

File tree

3 files changed

+13
-11
lines changed

3 files changed

+13
-11
lines changed

lib/Drupal/Core/KeyValueStore/DatabaseStorageExpirable.php

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -88,17 +88,11 @@ public function setWithExpire($key, $value, $expire) {
8888
* {@inheritdoc}
8989
*/
9090
public function setWithExpireIfNotExists($key, $value, $expire) {
91-
$result = $this->connection->merge($this->table)
92-
->insertFields([
93-
'collection' => $this->collection,
94-
'name' => $key,
95-
'value' => $this->serializer->encode($value),
96-
'expire' => REQUEST_TIME + $expire,
97-
])
98-
->condition('collection', $this->collection)
99-
->condition('name', $key)
100-
->execute();
101-
return $result == Merge::STATUS_INSERT;
91+
if (!$this->has($key)) {
92+
$this->setWithExpire($key, $value, $expire);
93+
return TRUE;
94+
}
95+
return FALSE;
10296
}
10397

10498
/**

lib/Drupal/Core/KeyValueStore/KeyValueStoreExpirableInterface.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ public function setWithExpire($key, $value, $expire);
2222
/**
2323
* Sets a value for a given key with a time to live if it does not yet exist.
2424
*
25+
* If a key is expired it also does not exists.
26+
*
2527
* @param string $key
2628
* The key of the data to store.
2729
* @param mixed $value

tests/Drupal/KernelTests/Core/KeyValueStore/DatabaseStorageExpirableTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,12 @@ public function testExpiration() {
153153
foreach (['troubles', 'still'] as $key) {
154154
$this->assertTrue(!empty($all[$key]));
155155
}
156+
157+
// Test DatabaseStorageExpirable::setWithExpireIfNotExists() will overwrite
158+
// expired items.
159+
$this->assertNull($stores[0]->get('yesterday'));
160+
$stores[0]->setWithExpireIfNotExists('yesterday', 'Oh, yesterday came suddenly', $day);
161+
$this->assertSame('Oh, yesterday came suddenly', $stores[0]->get('yesterday'));
156162
}
157163

158164
}

0 commit comments

Comments
 (0)