Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [[*next-version*]] - YYYY-MM-DD
### Fixed
- Setting same value as existing caused an exception due to false-negative result (#22).

## [0.2.0-alpha1] - 2023-08-30
### Removed
Expand Down
8 changes: 7 additions & 1 deletion src/CachePool.php
Original file line number Diff line number Diff line change
Expand Up @@ -350,14 +350,20 @@ protected function getTransientOriginal(string $key)
* @param int $ttl The amount of seconds after which the transient will expire.
*
* @throws RangeException If key invalid.
* @throws UnexpectedValueException If could not write the value to WP Transients API.
* @throws RuntimeException If problem setting.
*/
protected function setTransient(string $key, $value, int $ttl): void
{
$this->validateTransientKey($key);

if (!set_transient($key, $value, $ttl)) {
throw new RuntimeException(sprintf('set_transient() failed with key "%1$s" with TTL %2$ss', $key, $ttl));
$actualValue = $this->getTransient($key);
if ($actualValue !== $value) {
throw new UnexpectedValueException(
sprintf('set_transient() failed with key "%1$s" with TTL %2$ss', $key, $ttl)
);
}
}
}

Expand Down
31 changes: 31 additions & 0 deletions tests/functional/CachePoolTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -359,4 +359,35 @@ public function testHas()
$this->assertFalse($subject->has($notThereKey));
}
}

/**
* Imitates a scenario where `set_transient()` erroneously returns `false` if set value is same as existing.
*/
public function testWritingSameValueSucceeds()
{
{
$poolName = uniqid('pool');
$defaultValue = uniqid('default');
$wpdb = $this->createWpdb();
$key = uniqid('key');
$value = uniqid('value');
$subject = $this->createInstance($wpdb, $poolName, $defaultValue);
}

{
Functions\expect('get_transient')
->andReturn($value);
Functions\expect('set_transient')
->andReturn();
}

{
// If no exception - success
$subject->set($key, $value, rand(1, 99999));

// Problem setting a different value results in an exception
$this->expectException(CacheException::class);
$subject->set($key, uniqid('other-value'), rand(1, 99999));
}
}
}