saufen/src/Service/ConfigurationService.php
2025-06-08 21:22:26 +02:00

78 lines
2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Service;
use App\Entity\SystemConfig;
use App\Enum\SystemSettingKey;
use App\Repository\SystemConfigRepository;
use InvalidArgumentException;
readonly class ConfigurationService
{
public function __construct(
private SystemConfigRepository $systemConfigRepository,
) {}
/**
* Get all configuration entries
*
* @return SystemConfig[]
*/
public function getAllConfigs(): array
{
return $this->systemConfigRepository->findAll();
}
public function getConfigValue(SystemSettingKey $key, string $default = ''): string
{
return $this->systemConfigRepository->getValue($key, $default);
}
public function setConfigValue(SystemSettingKey $key, string $value): void
{
$this->systemConfigRepository->setValue($key, $value);
}
public function getConfigByKey(SystemSettingKey $key): SystemConfig
{
return $this->systemConfigRepository->findByKey($key);
}
public function createConfig(SystemSettingKey $key, string $value): SystemConfig
{
if ($this->systemConfigRepository->findByKey($key) instanceof SystemConfig) {
throw new InvalidArgumentException("A configuration with the key '{$key->value}' already exists");
}
$config = new SystemConfig();
$config->setKey($key);
$config->setValue($value);
$this->systemConfigRepository->save($config);
return $config;
}
public function updateConfig(SystemConfig $config, string $value): SystemConfig
{
if ($value !== '') {
$config->setValue($value);
}
$this->systemConfigRepository->save($config);
return $config;
}
public function resetAllConfigs(): void
{
foreach (SystemSettingKey::cases() as $key) {
$this->setDefaultValue($key);
}
}
public function setDefaultValue(SystemSettingKey $key): void
{
$this->setConfigValue($key, SystemSettingKey::getDefaultValue($key));
}
}