Config Variables - Improve config variable system and initialize variables during setup.

This commit is contained in:
2024-12-12 15:38:28 +01:00
parent 28afb11ac4
commit dcd0b5f064
10 changed files with 175 additions and 58 deletions
+61
View File
@@ -0,0 +1,61 @@
<?php
namespace App\Consts;
use App\Entity\ConfigVariable;
use App\Enum\ConfigVariableSectionEnum;
//Variable List Constants
// --> This constants contains all defined Config Variables. For each one a array is stored as [varKey => [varSection, varDefaultValue]].
class ConfigVariableConsts
{
public const CONFIG_COMPANY_NAME = ["CompanyName" => [ConfigVariableSectionEnum::Company, "SomniaRooms"]];
public const CONFIG_COMPANY_WEBSITE = ["CompanyWebsite" => [ConfigVariableSectionEnum::Company, "somnia.dev"]];
public const CONFIG_COMPANY_LOGO = ["CompanyLogo" => [ConfigVariableSectionEnum::Company, ""]];
public const CONFIG_COMPANY_ADDRESS = ["CompanyAddress" => [ConfigVariableSectionEnum::Company, ""]];
public const CONFIG_COMPANY_EMAIL = ["CompanyEmail" => [ConfigVariableSectionEnum::Company, ""]];
public const CONFIG_COMPANY_PHONE = ["CompanyPhone" => [ConfigVariableSectionEnum::Company, ""]];
public const CONFIG_FRONTEND_NIGHTSFORCONTACT = ["NightAmountForContactDialog" => [ConfigVariableSectionEnum::Frontend, "10"]];
public const CONFIG_FRONTEND_GUESTSFORCONTACT = ["GuestNumberForContactDialog" => [ConfigVariableSectionEnum::Frontend, "6"]];
public const CONFIG_FRONTEND_CONTACTDIALOGBEHAVIOUR = ["ContactDialogShowBehaviour" => [ConfigVariableSectionEnum::Frontend, "show"]];
public const CONFIG_FRONTEND_SHOWNONAVAILABLEROOMS = ["ShowNonAvailableRooms" => [ConfigVariableSectionEnum::Frontend, true]];
public const CONFIG_FRONTEND_SOMNIAATTRIBUTION = ["SomniaAttributionNotice" => [ConfigVariableSectionEnum::Frontend, "full"]];
public const CONFIG_FRONTEND_PHOTOASPECTRATIO = ["PhotoAspectRatio" => [ConfigVariableSectionEnum::Frontend, "4:3"]];
public const CONFIG_PRICES_PRICEMETHOD = ["TotalPriceMethod" => [ConfigVariableSectionEnum::API_PRICES, "SUM"]];
public const CONFIG_PRICES_FAREMETHOD = ["FareSelectionMethod" => [ConfigVariableSectionEnum::API_PRICES, "HIGHER"]];
public const CONFIG_API_NAXNIGHTS = ["MaxAllowedNightAmount" => [ConfigVariableSectionEnum::API_CONFIG, "20"]];
public const CONFIG_API_NAXGUESTS = ["MaxAllowedGuestNumber" => [ConfigVariableSectionEnum::API_CONFIG, "20"]];
public const CONFIG_INTERNAL_SETUP = ["SETUP_STATUS" => [ConfigVariableSectionEnum::Internal, "1"]];
public static function getKeyFromConstant(array $constant): string
{
return array_key_first($constant);
}
public static function GetAllDefinedConfigVariablesList(): array
{
return array_merge(
ConfigVariableConsts::CONFIG_COMPANY_NAME,
ConfigVariableConsts::CONFIG_COMPANY_WEBSITE,
ConfigVariableConsts::CONFIG_COMPANY_LOGO,
ConfigVariableConsts::CONFIG_COMPANY_ADDRESS,
ConfigVariableConsts::CONFIG_COMPANY_EMAIL,
ConfigVariableConsts::CONFIG_COMPANY_PHONE,
ConfigVariableConsts::CONFIG_FRONTEND_NIGHTSFORCONTACT,
ConfigVariableConsts::CONFIG_FRONTEND_GUESTSFORCONTACT,
ConfigVariableConsts::CONFIG_FRONTEND_CONTACTDIALOGBEHAVIOUR,
ConfigVariableConsts::CONFIG_FRONTEND_SHOWNONAVAILABLEROOMS,
ConfigVariableConsts::CONFIG_FRONTEND_SOMNIAATTRIBUTION,
ConfigVariableConsts::CONFIG_FRONTEND_PHOTOASPECTRATIO,
ConfigVariableConsts::CONFIG_PRICES_PRICEMETHOD,
ConfigVariableConsts::CONFIG_PRICES_FAREMETHOD,
ConfigVariableConsts::CONFIG_API_NAXNIGHTS,
ConfigVariableConsts::CONFIG_API_NAXGUESTS,
ConfigVariableConsts::CONFIG_INTERNAL_SETUP,
);
}
}
@@ -3,7 +3,8 @@
namespace App\Controller\Admin; namespace App\Controller\Admin;
use App\Entity\ConfigVariable; use App\Entity\ConfigVariable;
use App\Enum\ConfigSectionType; use App\Enum\ConfigVariableSectionEnum;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud; use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController; use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField; use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
@@ -21,9 +22,14 @@ class ConfigVariableCrudController extends AbstractCrudController
return $crud; return $crud;
} }
public function configureActions(Actions $actions): Actions
{
return $actions->disable("new", "delete");;
}
public function configureFields(string $pageName): iterable public function configureFields(string $pageName): iterable
{ {
yield ChoiceField::new ('section')->setChoices(ConfigSectionType::cases()); yield ChoiceField::new('section')->setChoices(ConfigVariableSectionEnum::cases());
yield TextField::new('key'); yield TextField::new('key');
yield TextField::new('value'); yield TextField::new('value');
} }
+6 -5
View File
@@ -2,6 +2,7 @@
namespace App\Controller; namespace App\Controller;
use App\Consts\ConfigVariableConsts;
use App\DTO\AppSetupConfig; use App\DTO\AppSetupConfig;
use App\DTO\ExampleDataConfig; use App\DTO\ExampleDataConfig;
use App\Entity\ConfigVariable; use App\Entity\ConfigVariable;
@@ -9,9 +10,9 @@ use App\Form\AppSetupFormType;
use App\Form\ExampleDataFormType; use App\Form\ExampleDataFormType;
use App\Repository\RoomCategoryRepository; use App\Repository\RoomCategoryRepository;
use App\Service\AppSetupService; use App\Service\AppSetupService;
use App\Service\ConfigVariableService;
use App\Service\ExampleDataService; use App\Service\ExampleDataService;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Monolog\Logger;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -25,13 +26,13 @@ class AppSetupController extends AbstractController
LoggerInterface $logger, LoggerInterface $logger,
AppSetupService $setupService, AppSetupService $setupService,
Request $request, Request $request,
EntityManagerInterface $entityManager ConfigVariableService $configVars
): Response { ): Response {
$configRepo = $entityManager->getRepository(ConfigVariable::class); $setupVar_key = ConfigVariableConsts::getKeyFromConstant(ConfigVariableConsts::CONFIG_INTERNAL_SETUP);
$setupStatus = $configRepo->findBy(["key" => "SETUP_STATUS"]); $setupStatus = $configVars->getVariable($setupVar_key);
if ($setupStatus != null && $setupStatus[0] != null && $setupStatus[0]->getValue() == 1) { if ($setupStatus != null && $setupStatus->getValue()) {
$logger->warning("SomniaRooms was already setup"); $logger->warning("SomniaRooms was already setup");
return $this->GoToResultPage( return $this->GoToResultPage(
+6 -6
View File
@@ -3,22 +3,22 @@
namespace App\Entity; namespace App\Entity;
use App\Repository\ConfigVariableRepository; use App\Repository\ConfigVariableRepository;
use App\Enum\ConfigSectionType; use App\Enum\ConfigVariableSectionEnum;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ConfigVariableRepository::class)] #[ORM\Entity(repositoryClass: ConfigVariableRepository::class)]
class ConfigVariable class ConfigVariable
{ {
#[ORM\Id] #[ORM\Id]
#[ORM\GeneratedValue("NONE")] #[ORM\GeneratedValue(strategy: "NONE")]
#[ORM\Column(length: 32, unique: true, nullable: false)] #[ORM\Column(length: 32, unique: true, nullable: false)]
private string $key = ""; private string $key = "";
#[ORM\Column(length: 255, nullable: false)] #[ORM\Column(length: 255, nullable: false)]
private ?string $value = null; private ?string $value = null;
#[ORM\Column(type: 'string', enumType: ConfigSectionType::class, nullable: false)] #[ORM\Column(type: 'string', enumType: ConfigVariableSectionEnum::class, nullable: false)]
private ConfigSectionType $section = ConfigSectionType::General; private ConfigVariableSectionEnum $section = ConfigVariableSectionEnum::Internal;
public function getKey(): string public function getKey(): string
@@ -45,12 +45,12 @@ class ConfigVariable
return $this; return $this;
} }
public function getSection(): ConfigSectionType public function getSection(): ConfigVariableSectionEnum
{ {
return $this->section; return $this->section;
} }
public function setSection(ConfigSectionType $section): static public function setSection(ConfigVariableSectionEnum $section): static
{ {
$this->section = $section; $this->section = $section;
-12
View File
@@ -1,12 +0,0 @@
<?php
namespace App\Enum;
enum ConfigSectionType: string {
case General = 'GENERAL';
case Internal = 'INTERNAL';
case Company = 'COMPANY';
case Backend = 'BACK';
case Frontend = 'FRONT';
case Test = 'TEST';
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace App\Enum;
enum ConfigVariableSectionEnum: string
{
case Company = 'COMPANY';
case Frontend = 'FRONTEND_CONFIG';
case API_PRICES = 'API_PRICES';
case API_CONFIG = 'API_CONFIG';
case Internal = 'INTERNAL';
}
+28 -3
View File
@@ -5,6 +5,7 @@ namespace App\Repository;
use App\Entity\ConfigVariable; use App\Entity\ConfigVariable;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\ManagerRegistry;
use Ds\Set;
/** /**
* @extends ServiceEntityRepository<ConfigVariable> * @extends ServiceEntityRepository<ConfigVariable>
@@ -51,14 +52,24 @@ class ConfigVariableRepository extends ServiceEntityRepository
* @param string Variable Key * @param string Variable Key
* @return ConfigVariable|null Config Variable. * @return ConfigVariable|null Config Variable.
*/ */
public function findVariableByKey($varKey) public function findVariableByKey($varKey): ConfigVariable|null
{ {
return $this->createQueryBuilder('c') $rs = $this->createQueryBuilder('c')
->select('c.key, c.value, c.section') ->select('c.key, c.value, c.section')
->andWhere('c.key = :val') ->andWhere('c.key = :val')
->setParameter('val', $varKey) ->setParameter('val', $varKey)
->setMaxResults(1)
->getQuery() ->getQuery()
->getOneOrNullResult(); ->getResult();
// FIXME!!!
if (!$rs) {
return null;
}
$var = new ConfigVariable();
$var->setKey($rs[0]["key"]);
$var->setValue($rs[0]["value"]);
$var->setSection($rs[0]["section"]);
return $var;
} }
/** /**
@@ -73,4 +84,18 @@ class ConfigVariableRepository extends ServiceEntityRepository
->getQuery() ->getQuery()
->getResult(); ->getResult();
} }
/**
* Get all DB config variables names on a Set.
* @return Set Returns a Set with all variable names.
*/
public function getVariableSet(): Set
{
$varList = $this->findAll();
$keyList = array_map(function ($var) {
return $var->getKey();
}, $varList);
return new Set($keyList);
}
} }
+14 -12
View File
@@ -2,10 +2,11 @@
namespace App\Service; namespace App\Service;
use App\Consts\ConfigVariableConsts;
use App\DTO\AppSetupConfig; use App\DTO\AppSetupConfig;
use App\Entity\ConfigVariable; use App\Entity\ConfigVariable;
use App\Entity\User; use App\Entity\User;
use App\Enum\ConfigSectionType; use App\Enum\ConfigVariableSectionEnum;
use App\Enum\UserRoleEnum; use App\Enum\UserRoleEnum;
use App\Repository\ConfigVariableRepository; use App\Repository\ConfigVariableRepository;
@@ -23,7 +24,7 @@ class AppSetupService
public function __construct( public function __construct(
private LoggerInterface $logger, private LoggerInterface $logger,
private EntityManagerInterface $entityManager, private EntityManagerInterface $entityManager,
private ConfigVariableRepository $repoVariables, private ConfigVariableService $configVars,
private UserPasswordHasherInterface $passwordHasher, private UserPasswordHasherInterface $passwordHasher,
private Security $security private Security $security
) {} ) {}
@@ -37,15 +38,18 @@ class AppSetupService
//Create system variables. //Create system variables.
$this->logger->info("SomniaRooms Setup - Creating system variables..."); $this->logger->info("SomniaRooms Setup - Creating system variables...");
$var_setup = $this->repoVariables->find("SETUP_STATUS"); //Not neccesary anymore. CONFIG_INTERNAL_SETUP will be initialized with all vars.
if (!$var_setup) { // $var_setup_key = ConfigVariableConsts::getKeyFromConstant(ConfigVariableConsts::CONFIG_INTERNAL_SETUP);
$var_setup = new ConfigVariable(); // $var_setup = $this->configVars->getVariable($var_setup_key);
$var_setup->setKey("SETUP_STATUS"); // if (!$var_setup) {
} // $var_setup = new ConfigVariable();
$var_setup->setValue("1"); // $var_setup->setKey($var_setup_key);
$var_setup->setSection(ConfigSectionType::Internal); // $this->entityManager->persist($var_setup);
$this->entityManager->persist($var_setup); // }
// $var_setup->setValue("1");
// $var_setup->setSection(ConfigVariableSectionEnum::Internal);
$this->configVars->InitVariablesOnSetup();
//Create user Admin. //Create user Admin.
$this->logger->info("SomniaRooms Setup - Adding super-admin user..."); $this->logger->info("SomniaRooms Setup - Adding super-admin user...");
@@ -53,8 +57,6 @@ class AppSetupService
$user->setRoles([UserRoleEnum::ROLE_USER->value, UserRoleEnum::ROLE_ADMIN->value, UserRoleEnum::ROLE_SUPERADMIN->value]); $user->setRoles([UserRoleEnum::ROLE_USER->value, UserRoleEnum::ROLE_ADMIN->value, UserRoleEnum::ROLE_SUPERADMIN->value]);
$plaintextPassword = $configData->getAdminPass(); $plaintextPassword = $configData->getAdminPass();
// hash the password (based on the security.yaml config for the $user class) // hash the password (based on the security.yaml config for the $user class)
$hashedPassword = $this->passwordHasher->hashPassword( $hashedPassword = $this->passwordHasher->hashPassword(
$user, $user,
+35 -12
View File
@@ -2,10 +2,14 @@
namespace App\Service; namespace App\Service;
use App\Consts\ConfigVariableConsts;
use App\Entity\ConfigVariable; use App\Entity\ConfigVariable;
use App\Enum\ConfigVariableSectionEnum;
use App\Repository\ConfigVariableRepository; use App\Repository\ConfigVariableRepository;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
/** /**
* Service to manage config variables. * Service to manage config variables.
@@ -14,33 +18,52 @@ class ConfigVariableService
{ {
public function __construct( public function __construct(
private ConfigVariableRepository $repoVariables private EntityManagerInterface $entityManager,
private ConfigVariableRepository $repoVariables,
private LoggerInterface $logger,
) {} ) {}
public function getVariable(string $key) { public function getVariable(string $key): ConfigVariable|null
$var = $this->repoVariables->findVariableByKey($key); {
return $this->repoVariables->findVariableByKey($key);
} }
/** /**
* Create and init all variables. * Create and init all variables.
* To be used during Setup process. * To be used during Setup process.
*/ */
public function InitVariablesOnSetup(): void { public function InitVariablesOnSetup(): void
{
//Get a list of variables to check if those already exists.
//$this->entityManager->beginTransaction();
$varListDb = $this->repoVariables->getVariableSet();
$varListPHP = ConfigVariableConsts::GetAllDefinedConfigVariablesList();
$entityManager = $this->repoVariables->getEntityManager(); foreach ($varListPHP as $varKey => $varValue) {
$entityManager->beginTransaction(); if ($varListDb->contains($varKey)) {
$this->logger->info("Var $varKey already created. Skipped!", [$varKey, $varValue]);
continue;
}
$this->AddConfigVariable($varKey, $varValue[1], $varValue[0]);
}
try { try {
} catch (\Throwable $th) {
} $this->entityManager->rollback();
catch (\Throwable $th) {
$entityManager->rollback();
throw $th; throw $th;
} }
} }
private function AddConfigVariable(string $key, string $value, string $section): void { public function AddConfigVariable(string $key, string $value, ConfigVariableSectionEnum $section): void
{
$var = new ConfigVariable();
$var->setKey($key);
$var->setValue($value);
$var->setSection($section);
} $this->entityManager->persist($var);
$this->logger->info("Variable added to DB", ["key" => $key, "value" => $value, "section" => $section]);
}
} }
-1
View File
@@ -9,7 +9,6 @@ use App\Entity\FareTable;
use App\Entity\RoomCategory; use App\Entity\RoomCategory;
use App\Entity\RoomFare; use App\Entity\RoomFare;
use App\Entity\User; use App\Entity\User;
use App\Enum\ConfigSectionType;
use App\Enum\UserRoleEnum; use App\Enum\UserRoleEnum;
use App\Repository\ConfigVariableRepository; use App\Repository\ConfigVariableRepository;
use App\Repository\FareTableRepository; use App\Repository\FareTableRepository;