meobda-website/app/Services/SiteDataService.php

74 lines
1.9 KiB
PHP

<?php
namespace App\Services;
use App\Models\SiteDataItem;
use InvalidArgumentException;
class SiteDataService
{
public function __construct(
protected array $defaults = [],
protected string $cacheKeyPrefix = '',
) {
$this->defaults = config('siteData.defaults', []);
$this->cacheKeyPrefix = config('siteData.cache_key_prefix', 'site_data_');
}
public function get(string $key): mixed
{
$this->ensureKeyExists($key);
$cacheKey = $this->cacheKeyPrefix.$key;
return cache()->remember($cacheKey, now()->addDay(), function () use ($key) {
$dataItem = SiteDataItem::find($key);
$value = $dataItem?->value ?? $this->defaults[$key]['value'];
$type = $dataItem?->type ?? $this->defaults[$key]['type'];
return $type === 'json' ? json_decode($value, true) : $value;
});
}
public function set(string $key, string|array $value, ?string $type = null): void
{
$this->ensureKeyExists($key);
$cacheKey = $this->cacheKeyPrefix.$key;
cache()->forget($cacheKey);
$type = $type ?? $this->defaults[$key]['type'];
if (is_array($value)) {
$value = json_encode($value);
$type = 'json';
}
SiteDataItem::updateOrCreate(
['key' => $key],
['value' => $value, 'type' => $type]
);
}
public function has(string $key): bool
{
return isset($this->defaults[$key]);
}
public function forget(string $key): void
{
$this->ensureKeyExists($key);
$cacheKey = $this->cacheKeyPrefix.$key;
cache()->forget($cacheKey);
}
protected function ensureKeyExists(string $key): void
{
if (! $this->has($key)) {
throw new InvalidArgumentException("Site data key [{$key}] is not defined in configuration.");
}
}
}