Skip to content

Commit

Permalink
Add ability to get the cache key for a given setting key
Browse files Browse the repository at this point in the history
  • Loading branch information
rawilk committed Sep 28, 2023
1 parent 5372bb1 commit 91fbd87
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Facades/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
* @method static self disableTeams()
* @method static bool teamsAreEnabled()
* @method static \Rawilk\Settings\Contracts\KeyGenerator getKeyGenerator()
* @method static string cacheKeyForSetting(string $key)
*/
class Settings extends Facade
{
Expand Down
21 changes: 21 additions & 0 deletions src/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,27 @@ public function getKeyGenerator(): KeyGenerator
return $this->keyGenerator;
}

/**
* Generate the key to use for caching a specific setting.
* This is meant for external usage.
*/
public function cacheKeyForSetting(string $key): string
{
$storageKey = $this->getKeyForStorage(
$this->normalizeKey($key),
);

$cacheKey = $this->getCacheKey($storageKey);

if ($this->resetContext) {
$this->context();
}

$this->resetContext = true;

return $cacheKey;
}

protected function normalizeKey(string $key): string
{
if (Str::startsWith(haystack: $key, needles: 'file_')) {
Expand Down
14 changes: 14 additions & 0 deletions tests/Feature/SettingsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,20 @@
Event::assertDispatchedTimes(SettingWasStored::class, 1);
});

it('can generate the cache key for a given setting', function () {
$settings = settings();
$settings->useCacheKeyPrefix('settings.');
(fn () => $this->keyGenerator = (new ReadableKeyGenerator)->setContextSerializer(new DotNotationContextSerializer))->call($settings);

expect(SettingsFacade::cacheKeyForSetting('foo'))->toBe('settings.foo')
->and(SettingsFacade::context(new Context(['foo' => 'bar']))->cacheKeyForSetting('foo'))->toBe('settings.foo:c:::foo:bar');

SettingsFacade::enableTeams();
SettingsFacade::setTeamId(1);

expect(SettingsFacade::cacheKeyForSetting('foo'))->toBe('settings.foo::team:1');
});

// Helpers...

function assertQueryCount(int $expected): void
Expand Down

0 comments on commit 91fbd87

Please sign in to comment.