Skip to content

Commit b588cc0

Browse files
committed
Prevent reading config file when it doesn’t exist
1 parent 2f21186 commit b588cc0

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

app/Providers/AppServiceProvider.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,12 @@ class AppServiceProvider extends ServiceProvider
1111
{
1212
public function register(): void
1313
{
14+
$this->app->singleton(
15+
ConfigManager::class,
16+
static fn () => new ConfigManager($_SERVER['HOME'] . '/.config/chief'),
17+
);
18+
1419
$this->app->singleton(AuthService::class);
15-
$this->app->singleton(ConfigManager::class);
1620
$this->app->singleton(DomainChiefService::class);
1721
}
1822
}

app/Services/ConfigManager.php

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,13 @@ class ConfigManager
1414
'team_name' => null,
1515
];
1616

17-
private string $basePath;
18-
1917
/** @var array<string, mixed> */
2018
private array $config;
2119

22-
public function __construct()
23-
{
24-
$this->basePath = $_SERVER['HOME'] . '/.config/chief';
25-
26-
if (!$this->ensureConfigDirectory()) {
27-
throw new RuntimeException("Unable to create config directory: {$this->basePath}");
28-
}
29-
20+
public function __construct(
21+
private readonly string $basePath,
22+
) {
3023
$this->readConfig();
31-
32-
if (!file_exists($this->getConfigFilePath())) {
33-
$this->writeConfig();
34-
}
3524
}
3625

3726
public function get(string $key, $default = null)
@@ -76,6 +65,12 @@ public function reset(): void
7665

7766
private function readConfig(): void
7867
{
68+
if (!file_exists($this->getConfigFilePath())) {
69+
$this->config = self::DEFAULT_CONFIG;
70+
71+
return;
72+
}
73+
7974
try {
8075
$loadedConfig = require $this->getConfigFilePath();
8176

@@ -89,6 +84,10 @@ private function readConfig(): void
8984

9085
private function writeConfig(): void
9186
{
87+
if (!$this->ensureConfigDirectoryExists()) {
88+
throw new RuntimeException("Unable to create config directory: {$this->basePath}");
89+
}
90+
9291
$fileContents = '<?php' . PHP_EOL . PHP_EOL . 'return ' . var_export($this->config, true) . ';' . PHP_EOL;
9392

9493
if (!file_put_contents($this->getConfigFilePath(), $fileContents)) {
@@ -101,7 +100,7 @@ private function getConfigFilePath(): string
101100
return $this->basePath . '/config.php';
102101
}
103102

104-
private function ensureConfigDirectory(): bool
103+
private function ensureConfigDirectoryExists(): bool
105104
{
106105
if (is_dir($this->basePath)) {
107106
return true;

0 commit comments

Comments
 (0)