bindAPI/src/Controller/ConfigController.php

66 lines
2.3 KiB
PHP

<?php
namespace App\Controller;
use App\Utilities\Colors;
class ConfigController
{
private array $config;
private static $missingEncryptionShown = false;
public function __construct(private readonly bool $quiet, bool $test = false)
{
if ($test) {
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json.test";
if (!file_exists(filename: $configFile)) {
echo 'No testing (config.json.test) config has benn setup.' . PHP_EOL;
exit(1);
}
} else {
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json.local";
if (!file_exists(filename: $configFile)) {
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json";
}
if (!file_exists(filename: $configFile)) {
echo 'Missing config file' . PHP_EOL;
if (confirm(message: 'Should I create a new config based on config.json.sample?')) {
copy(from: 'config.json.sample', to: 'config.json');
echo 'Config file has been generated. Adjust it to your needs, then proceed to database setup.' . PHP_EOL;
} else {
echo 'You first have to setup the bindAPI. Bye.' . PHP_EOL;
exit(0);
}
exit(1);
}
}
$configJSON = file_get_contents(filename: $configFile);
// first check if json is valid, after make the assignment
if (json_decode(json: $configJSON, associative: true) === null) {
echo 'Config file is not valid JSON.' . PHP_EOL;
echo $configJSON . PHP_EOL;
exit(1);
}
$this->config = json_decode(json: $configJSON, associative: true);
if (!ConfigController::$missingEncryptionShown) {
if ($this->config['encryptionKey'] === '1bad::babe') {
ConfigController::$missingEncryptionShown = true;
if (!$this->quiet) {
echo Colors::RED . 'Error: ' . Colors::DEFAULT . 'No encryption key, please run ' . Colors::YELLOW . './bin/console check:generatekey' . Colors::DEFAULT . PHP_EOL;
}
}
}
}
public function getConfig(string $configKey): string
{
return $this->config[$configKey];
}
}