Files
laravel-manager-packagist/src/Support/Settings/Writer.php
T
2026-12-04 17:50:18 +00:00

78 lines
2.1 KiB
PHP

<?php
namespace IriksIT\Manager\Support\Settings;
use Illuminate\Support\Facades\Artisan;
use Throwable;
/** Saves changes to settings: the table and the compiled file, the config of this request, and `.env` when the site allows it. */
class Writer
{
public function __construct(private readonly Definitions $definitions, private readonly Store $store, private readonly EnvFile $env) {}
/**
* @param array<string, mixed> $changes config path => value; null puts the setting back to what the config says
* @return array{file_written: bool, env_written: bool}
*/
public function apply(array $changes, mixed $userId = null): array
{
if ($changes === []) {
return ['file_written' => true, 'env_written' => false];
}
$written = $this->store->put($changes, $userId);
foreach ($changes as $key => $value) {
config([$key => $value ?? config($key)]);
}
return ['file_written' => $written, 'env_written' => $this->writeEnv($changes)];
}
/** Writes the compiled file again and empties what caches the old values. */
public function refresh(): bool
{
$written = $this->store->compile();
function_exists('opcache_reset') && @opcache_reset();
$this->recache();
return $written;
}
/** @param array<string, mixed> $changes */
private function writeEnv(array $changes): bool
{
if (! config('manager.settings.write_env')) {
return false;
}
$pairs = [];
foreach ($changes as $key => $value) {
$env = $this->definitions->find($key)['env'] ?? null;
if ($env !== null && $value !== null) {
$pairs[$env] = $value;
}
}
$done = $this->env->set($pairs);
$done && $this->recache();
return $done;
}
private function recache(): void
{
if (! app()->configurationIsCached()) {
return;
}
try {
Artisan::call('config:cache');
} catch (Throwable) {
// The overlay still applies on top of a config cache that is a bit old.
}
}
}