6
0
Fork 0
jiqu-library-server/app/Services/SettingService.php

124 lines
2.8 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;
use Throwable;
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);
}
if (! array_key_exists($key, $this->items)) {
try {
$this->items[$key] = $this->cache->remember($this->cacheKey($key), $this->ttl, function () use ($key) {
$_key = $this->keyHandle($key);
$settings = Setting::where('key', $_key[0])->firstOrFail();
if (isset($_key[1])) {
return Arr::get($settings->value, $_key[1]);
} else {
return $settings->value;
}
});
} catch (ModelNotFoundException $e) {
return $default;
} catch (Throwable $th) {
return $default;
}
}
return $this->items[$key];
}
/**
* @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->keyHandle($key);
Setting::where('key', $_key[0])->update(['value->'.$_key[1] => $value]);
$this->cleanCache($key);
}
}
/**
* @param string $key
* @return void
*/
public function cleanCache(string $key): void
{
unset($this->items[$key]);
$this->cache->forget($this->cacheKey($key));
}
/**
* @param string $key
* @return string
*/
protected function cacheKey(string $key): string
{
return "settings.{$key}";
}
protected function keyHandle(string $key)
{
return explode('.', $key);
}
}