|
- <?php
-
- namespace common\logic\Setting;
-
- use common\logic\AbstractBuilder;
- use yii\base\ErrorException;
-
- class SettingBuilder extends AbstractBuilder
- {
- protected SettingDefinition $settingDefinition;
- protected SettingRepository $settingRepository;
-
- public function loadDependencies(): void
- {
- $this->settingDefinition = $this->loadService(SettingDefinition::class);
- $this->settingRepository = $this->loadService(SettingRepository::class);
- }
-
- public function instanciateSetting(
- string $name
- ): Setting
- {
- $setting = new Setting();
- $setting->name = $name;
- $setting->populateProducer($this->getProducerContext(false));
- $this->initDefaultValue($setting);
-
- return $setting;
- }
-
- public function createSetting(
- string $name
- ): Setting
- {
- $setting = $this->settingRepository->findOneSettingByName($name);
- if(!$setting) {
- $setting = $this->instanciateSetting($name);
- $this->create($setting);
- }
-
- return $setting;
- }
-
- public function initValue(Setting $setting, $value)
- {
- $settingDetail = $this->settingDefinition->getSettingDetailByName($setting->name);
- $type = $settingDetail->getType();
- if(in_array($type, ['string', 'text', 'date', 'integer', 'float', 'double', 'boolean'])) {
- $setting->$type = $value;
- }
- else {
- throw new ErrorException("Le type de donnée n'est pas reconnu.");
- }
- }
-
- public function initDefaultValue(Setting $setting)
- {
- $settingDetail = $this->settingDefinition->getSettingDetailByName($setting->name);
- if($settingDetail->getDefaultValue()) {
- $this->initValue($setting, $settingDetail->getDefaultValue());
- }
- }
-
- public function updateValueByName(string $name, $value): void
- {
- $setting = $this->createSetting($name);
- $this->initValue($setting, $value);
- $this->update($setting);
- }
-
- public function updateDefaultValueByName(string $name)
- {
- $setting = $this->createSetting($name);
- $this->initDefaultValue($setting);
- $this->update($setting);
- }
- }
|