Skip to content

Commit

Permalink
Refactor SettingService into LazySetting class
Browse files Browse the repository at this point in the history
The SettingsService class has been deleted and its functionality moved into the LazySetting class. The provider and configuration file have also been adjusted to match these changes. This refactoring improves our structure by centralizing setting management in one class.
  • Loading branch information
CrazyBoy49z committed Jul 6, 2024
1 parent d892bfc commit 517a9d7
Show file tree
Hide file tree
Showing 4 changed files with 221 additions and 230 deletions.
9 changes: 4 additions & 5 deletions config/lazy/setting.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@
return [
'table' => 'settings',
'cache_key' => 'cache-settings',
'cache_ttl' => 60 * 60 * 24,
'cache_ttl' => null, // in seconds (default: forever)
'default' => [
'group' => 'string',
'type' => 'text',
'group' => 'default',
'type' => 'string',
'value' => null,
'is_protected' => false,
'options' => [],
'is_encrypted' => false,
'deletable' => true,
],
];
217 changes: 216 additions & 1 deletion src/LazySetting.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,219 @@

namespace Step2Dev\LazySetting;

class LazySetting {}
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Step2Dev\LazySetting\Models\Setting;
use InvalidArgumentException;
use Throwable;

class LazySetting
{
private Collection $settings;

public function __construct()
{
$this->settings = Collection::make();
}

public static function getCacheKey(): string
{
return config('lazy-setting.cache_key', self::getCacheKey());
}

public static function getCacheTtl(): int
{
return config('lazy-setting.cache_ttl');
}

public static function getDefaultGroup(): string
{
return config('lazy-setting.default.group', 'default');
}

public static function getDefaultType(): string
{
return config('lazy-setting.default.type', 'string');
}

public function init(): static
{
if ($this->settings->isEmpty()) {
$this->settings = cache()->rememberForever(self::getCacheKey(), fn () => Setting::get());
}

return $this;
}

public function getSettings(): Collection
{
return $this->init()->settings;
}

/**
* @throws Throwable
*/
public function getKeyAndGroup(string $key): array
{
[$key, $group] = array_pad(
array_reverse(explode('.', $key, 2)),
2, null);

$key = trim((string) $key);

throw_if(! $key, new InvalidArgumentException('Key cannot be null or empty example: "app.name" or "name" received: "'.$group.'.'.$key.'"'));

$group = trim((string) $group) ?: self::getDefaultGroup();

return compact('key', 'group');
}

public function get(string $key, mixed $default = null): string|null
{
return $this->getConfig($key)?->value ?? $default;
}

public function getConfig(string $key): Setting|null
{
try {
['group' => $group, 'key' => $key] = $this->getKeyAndGroup($key);
} catch (InvalidArgumentException|Throwable $e) {
Log::error(__METHOD__.' '.$e->getMessage());

return null;
}

return $this->getSettings()
->where('group', $group)
->firstWhere('key', $key);
}

/**
* @throws Throwable
*/
public function set(string $key, mixed $data, string|null $type = null): Setting
{
if ($setting = $this->getConfig($key)) {
$this->update($setting, $data);
} else {
$setting = $this->createIfNotExists($key, $data, $type);
}

return $setting;
}

public function all(): Collection
{
return $this->getSettings();
}

public function update(Setting $setting, mixed $data): Setting
{
$setting->update($this->formatData($data, $setting->type));

$this->clearCache();

return $setting;
}

/**
* @throws Throwable
*/
public function createIfNotExists(string $key, mixed $data, string|null $type = null): Setting
{
$setting = Setting::firstOrCreate($this->getKeyAndGroup($key), $this->formatData($data, $type));

$this->clearCache();

return $setting;
}

public function getFieldType(string $type = ''): string
{
$type = strtolower(trim($type));

return match ($type) {
'string', 'text', 'textarea', 'richtext' => 'string',
'integer', 'int' => 'integer',
'float', 'double' => 'float',
'boolean', 'bool' => 'boolean',
'array' => 'array',
'json' => 'json',
'image' => 'image',
default => self::getDefaultType(),
};
}

final protected function formatData(array|string $data, string|null $type = null, ?array $options = []): array
{
$type = $this->getFieldType($type);
$result = compact('type');

if (! is_array($data)) {
return [...$result, 'value' => $data];
}

if (! isset($data['value'])) {
return $result;
}

$data['options'] ??= $options ?? [];

$result = [...$result, ...$data];

if (is_array($data['value'])) {
$result['value'] = json_encode($data['value'], JSON_THROW_ON_ERROR);
}

return $result;
}

/**
* @throws Throwable
*/
public function create(string $key, array $data, string|null $type = null): Setting
{
$setting = Setting::create([
...$this->getKeyAndGroup($key),
'type' => $type ?? 'string',
'value' => $data,
]);

$this->clearCache();

return $setting;
}

private function clearCache(bool $refresh = true): void
{
cache()->forget(self::getCacheKey());

if ($refresh) {
$this->init();
}
}

public function delete(string $key): void
{
$setting = $this->getConfig($key);

$setting?->delete();

$this->clearCache();
}

public function getTypes(): array
{
return [
'string',
'integer',
'float',
'boolean',
'array',
'json',
'image',
'richtext',
'textarea',
];
}
}
3 changes: 1 addition & 2 deletions src/LazySettingServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;
use Step2Dev\LazySetting\Commands\LazySettingCommand;
use Step2Dev\LazySetting\Services\SettingService;

class LazySettingServiceProvider extends PackageServiceProvider
{
Expand All @@ -26,6 +25,6 @@ public function configurePackage(Package $package): void

public function registeringPackage(): void
{
$this->app->singleton('setting', fn () => new SettingService());
$this->app->singleton('setting', fn () => new LazySetting());
}
}
Loading

0 comments on commit 517a9d7

Please sign in to comment.