Skip to content

Commit

Permalink
Add Settings Extender
Browse files Browse the repository at this point in the history
  • Loading branch information
SychO9 committed Nov 12, 2020
1 parent 0c95774 commit 859d192
Showing 1 changed file with 84 additions and 0 deletions.
84 changes: 84 additions & 0 deletions src/Extend/Settings.php
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;
};
}
}
}

0 comments on commit 859d192

Please sign in to comment.