Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow resetting settings to default #3935

Merged
merged 8 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
27 changes: 27 additions & 0 deletions framework/core/src/Extend/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class Settings implements ExtenderInterface
private array $settings = [];
private array $defaults = [];
private array $lessConfigs = [];
private array $forget = [];

/**
* Serialize a setting value to the ForumSerializer attributes.
Expand Down Expand Up @@ -60,6 +61,18 @@ public function default(string $key, mixed $value): self
return $this;
}

/**
* Reset a setting to default when callback returns true.
* @param string $key: The key of the setting.
* @param (callable(mixed $value): bool)|bool $callback: Boolean to determine whether the setting needs deleted.
*/
public function forget(string $key, callable|bool $callback): self
{
$this->forget[$key] = $callback;

return $this;
}

/**
* Register a setting as a LESS configuration variable.
*
Expand Down Expand Up @@ -98,6 +111,20 @@ public function extend(Container $container, Extension $extension = null): void
});
}

if (! empty($this->forget)) {
$settings = $container->make(SettingsRepositoryInterface::class);

foreach ($this->forget as $key => $callback) {
$value = $settings->get($key);
$callback = ContainerUtil::wrapCallback($callback, $container);
$shouldForget = $callback($value);

if ($shouldForget) {
$settings->delete($key);
}
}
}

if (! empty($this->settings)) {
AbstractSerializer::addAttributeMutator(
ForumSerializer::class,
Expand Down
23 changes: 23 additions & 0 deletions framework/core/tests/integration/extenders/SettingsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,29 @@ public function null_custom_setting_returns_null()
$this->assertEquals(null, $value);
}

/**
* @test
*/
public function forgetting_setting_returns_default_value()
{
$this->setting('custom-prefix.forget_this_setting', '');

$this->extend(
(new Extend\Settings())
->default('custom-prefix.forget_this_setting', 'extenderDefault')
->forget('custom-prefix.forget_this_setting', function (mixed $value): bool {
return $value === '';
})
);

$value = $this->app()
->getContainer()
->make('flarum.settings')
->get('custom-prefix.forget_this_setting');

$this->assertEquals('extenderDefault', $value);
}

/**
* @test
*/
Expand Down
Loading