114 lines
2.3 KiB
PHP
114 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Setting;
|
|
use Illuminate\Contracts\Cache\Repository as Cache;
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
|
|
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) {
|
|
$settings = Setting::where('key', $key)->firstOrFail();
|
|
|
|
return $settings->value;
|
|
});
|
|
} catch (ModelNotFoundException $e) {
|
|
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) {
|
|
Setting::updateOrCreate([
|
|
'key' => $key,
|
|
], [
|
|
'value' => $value,
|
|
]);
|
|
|
|
$this->cleanCache($key);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param string $key
|
|
* @return void
|
|
*/
|
|
protected 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}";
|
|
}
|
|
}
|