-
-
Notifications
You must be signed in to change notification settings - Fork 836
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
84 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of Flarum. | ||
* | ||
* For detailed copyright and license information, please view the | ||
* LICENSE file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Flarum\Extend; | ||
|
||
use Flarum\Extension\Extension; | ||
use Flarum\Settings\SettingsRepositoryInterface; | ||
use Illuminate\Contracts\Container\Container; | ||
|
||
class Settings implements ExtenderInterface | ||
{ | ||
private $settings = []; | ||
private $defaults = []; | ||
private $modifiers = []; | ||
|
||
/** | ||
* Serialize a setting value to the ForumSerializer attributes. | ||
* | ||
* @param string $attributeName: The attribute name to be used in the ForumSerializer attributes array. | ||
* @param string $key: The key of the setting. | ||
* @return $this | ||
*/ | ||
public function serializeToForum(string $attributeName, string $key) | ||
{ | ||
$this->settings[$key] = $attributeName; | ||
|
||
return $this; | ||
} | ||
|
||
/** | ||
* Set a default value for a setting selected for serialization. | ||
* | ||
* @param string $key | ||
* @param $value | ||
* @return $this | ||
*/ | ||
public function default(string $key, $value) | ||
{ | ||
$this->defaults[$key] = $value; | ||
|
||
return $this; | ||
} | ||
|
||
/** | ||
* Modify a setting's value. | ||
* | ||
* @param string $key | ||
* @param $callback | ||
* @return $this | ||
*/ | ||
public function modifier(string $key, $callback) | ||
{ | ||
$this->modifiers[$key] = $callback; | ||
|
||
return $this; | ||
} | ||
|
||
public function extend(Container $container, Extension $extension = null) | ||
{ | ||
if (! empty($this->settings)) { | ||
$callback = function ($attributes) use ($container) { | ||
$settings = $container->make(SettingsRepositoryInterface::class); | ||
|
||
foreach ($this->settings as $key => $attributeName) { | ||
$value = $settings->get($key, $this->defaults[$key] ?? null); | ||
|
||
if (isset($this->modifiers[$key])) { | ||
$value = $this->modifiers[$key]($value); | ||
} | ||
|
||
$attributes[$attributeName] = $value; | ||
} | ||
|
||
return $attributes; | ||
}; | ||
} | ||
} | ||
} |