144 lines
3.1 KiB
PHP
144 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Setting;
|
|
use Illuminate\Contracts\Cache\Repository as Cache;
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
use Illuminate\Support\Arr;
|
|
|
|
class SettingService
|
|
{
|
|
/**
|
|
* @var array
|
|
*/
|
|
protected $items = [];
|
|
|
|
/**
|
|
* @var integer
|
|
*/
|
|
protected $ttl = 1800;
|
|
|
|
/**
|
|
* @param \Illuminate\Contracts\Cache\Repository $cache
|
|
*/
|
|
public function __construct(
|
|
protected Cache $cache,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* @param array|string $key
|
|
* @param mixed $default
|
|
* @return mixed
|
|
*/
|
|
public function get($key, $default = null)
|
|
{
|
|
if (is_array($key)) {
|
|
return $this->getMany($key);
|
|
}
|
|
|
|
$_key = $this->getSettingKey($key);
|
|
|
|
if (! array_key_exists($_key, $this->items)) {
|
|
try {
|
|
$this->items[$_key] = $this->cache->remember($this->cacheKey($_key), $this->ttl, function () use ($_key) {
|
|
$settings = Setting::where('key', $_key)->firstOrFail();
|
|
|
|
return $settings->value;
|
|
});
|
|
} catch (ModelNotFoundException $e) {
|
|
return $default;
|
|
}
|
|
}
|
|
|
|
return Arr::get($this->items, $key, $default);
|
|
}
|
|
|
|
/**
|
|
* @param array $keys
|
|
* @return array
|
|
*/
|
|
public function getMany(array $keys)
|
|
{
|
|
$settings = [];
|
|
|
|
foreach ($keys as $key => $default) {
|
|
if (is_numeric($key)) {
|
|
[$key, $default] = [$default, null];
|
|
}
|
|
|
|
$settings[$key] = $this->get($key, $default);
|
|
}
|
|
|
|
return $settings;
|
|
}
|
|
|
|
/**
|
|
* @param array|string $key
|
|
* @param mixed $value
|
|
* @return void
|
|
*/
|
|
public function set($key, $value = null)
|
|
{
|
|
$keys = is_array($key) ? $key : [$key => $value];
|
|
|
|
foreach ($keys as $key => $value) {
|
|
$_key = $this->getSettingKey($key);
|
|
|
|
$setting = Setting::firstOrNew(['key' => $_key]);
|
|
|
|
if (strpos($key, '.') === false) {
|
|
$setting->value = $value;
|
|
} else {
|
|
$json = [$_key => $setting->value];
|
|
|
|
data_set($json, $key, $value);
|
|
|
|
$setting->value = $json[$_key];
|
|
}
|
|
$setting->save();
|
|
|
|
$this->cleanCache($key);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param string $key
|
|
* @return void
|
|
*/
|
|
public function cleanCache(string $key): void
|
|
{
|
|
$_key = $this->getSettingKey($key);
|
|
unset($this->items[$_key]);
|
|
|
|
$this->cache->forget($this->cacheKey($_key));
|
|
}
|
|
|
|
/**
|
|
* @param string $key
|
|
* @return string
|
|
*/
|
|
protected function cacheKey(string $key): string
|
|
{
|
|
return "settings.{$key}";
|
|
}
|
|
|
|
/**
|
|
* 获取设置项的 key
|
|
*
|
|
* @param string $key
|
|
* @return string
|
|
*/
|
|
protected function getSettingKey(string $key): string
|
|
{
|
|
if (strpos($key, '.') === false) {
|
|
return $key;
|
|
}
|
|
|
|
$segments = explode('.', $key);
|
|
|
|
return $segments[0];
|
|
}
|
|
}
|