<?php
declare(strict_types=1);
namespace App\Setting\Service;
use App\Setting\Mapper\SettingConfigMapper;
use Hyperf\Config\Annotation\Value;
use Hyperf\Redis\Redis;
use Mine\Abstracts\AbstractService;
use Psr\Container\ContainerInterface;
class SettingConfigService extends AbstractService
{
public $mapper;
protected $container;
protected $redis;
protected $prefix;
protected $cacheGroupName;
protected $cacheName;
public function __construct(SettingConfigMapper $mapper, ContainerInterface $container)
{
$this->mapper = $mapper;
$this->container = $container;
$this->setCacheGroupName($this->prefix . 'configGroup:');
$this->setCacheName($this->prefix . 'config:');
$this->redis = $this->container->get(Redis::class);
}
public function getSystemGroupConfig(): array
{
return $this->mapper->getConfigByGroup('system');
}
public function getExtendGroupConfig(): array
{
return $this->mapper->getConfigByGroup('extend');
}
public function getConfigByGroup(string $groupName): array
{
if (empty($groupName)) return [];
$cacheKey = $this->getCacheGroupName() . $groupName;
if ($data = $this->redis->get($cacheKey)) {
return unserialize($data);
} else {
$data = $this->mapper->getConfigByGroup($groupName);
if ($data) {
$this->redis->set($cacheKey, serialize($data));
return $data;
}
return [];
}
}
public function getConfigByKey(string $key): array
{
if (empty($key)) return [];
$cacheKey = $this->getCacheName() . $key;
if (($data = $this->redis->get($cacheKey))) {
return unserialize($data);
} else {
$data = $this->mapper->getConfigByKey($key);
if ($data) {
$this->redis->set($cacheKey, serialize($data));
return $data;
}
return [];
}
}
public function clearCache(): bool
{
$groupCache = $this->redis->keys($this->getCacheGroupName().'*');
$keyCache = $this->redis->keys($this->getCacheName().'*');
foreach ($groupCache as $item) {
$this->redis->del($item);
}
foreach($keyCache as $item) {
$this->redis->del($item);
}
return true;
}
public function saveSystemConfig(array $data): bool
{
foreach ($data as $key => $value) {
$this->mapper->updateConfig($key, $value);
}
$this->clearCache();
return true;
}
public function updated($data): bool
{
return $this->mapper->updateConfig($data['key'], $data['value']);
}
public function getCacheGroupName(): string
{
return $this->cacheGroupName;
}
public function setCacheGroupName(string $cacheGroupName): void
{
$this->cacheGroupName = $cacheGroupName;
}
public function getCacheName(): string
{
return $this->cacheName;
}
public function setCacheName(string $cacheName): void
{
$this->cacheName = $cacheName;
}
}