bootstrapPath('cache/manager-settings.php'); } /** Lays the saved settings over the config. Called while the provider registers; it must never fail the app. */ public static function overlay(): void { try { $values = is_file(self::file()) ? (array) (include self::file()) : self::fromTable(); foreach ($values as $key => $value) { if (is_array($value) && array_key_exists('__enc', $value)) { $value = json_decode(Crypt::decryptString((string) $value['__enc']), true); } config([$key => $value]); } self::applyEffects(array_keys($values)); } catch (Throwable) { // A missing table (before the first migrate), a changed APP_KEY, a broken file: the config keeps what it had. } } /** * What a changed config key has to do besides sitting in the config: the time zone and the language are also set on the running app, and * a mail setting makes the mailer be built again with the new values. * * @param list $keys */ public static function applyEffects(array $keys): void { if (in_array('app.timezone', $keys, true) && is_string(config('app.timezone'))) { @date_default_timezone_set(config('app.timezone')); } if (in_array('app.locale', $keys, true) && is_string(config('app.locale'))) { app()->setLocale(config('app.locale')); } if (array_filter($keys, fn ($key) => str_starts_with($key, 'mail.')) !== [] && app()->resolved('mail.manager')) { app('mail.manager')->purge(); } } /** @return array */ private static function fromTable(): array { $values = []; foreach (DB::table(Names::table('settings'))->get() as $row) { $values[$row->key] = $row->is_secret ? ['__enc' => $row->value] : json_decode((string) $row->value, true); } return $values; } /** * Saves values (null: back to what the config says) and rewrites the compiled file. Returns whether that file could be written. * * @param array $values by config path, already checked against the definitions */ public function put(array $values, mixed $userId = null): bool { $table = Names::table('settings'); DB::transaction(function () use ($values, $table, $userId) { foreach ($values as $key => $value) { $definition = $this->definitions->find($key); if ($value === null || $definition === null) { DB::table($table)->where('key', $key)->delete(); continue; } $secret = $definition['type'] === 'secret'; $stored = $secret ? Crypt::encryptString(json_encode($value)) : json_encode($value); DB::table($table)->updateOrInsert(['key' => $key], ['value' => $stored, 'is_secret' => $secret, 'updated_by' => $userId, 'updated_at' => now(), 'created_at' => now()]); } }); return $this->compile(); } /** Writes the compiled file from the table: to a temporary file first, then moved over the old one in one step. */ public function compile(): bool { $known = $this->definitions->all(); $values = array_filter(self::fromTable(), fn ($value, $key) => isset($known[$key]), ARRAY_FILTER_USE_BOTH); $file = self::file(); $temporary = $file.'.'.bin2hex(random_bytes(4)).'.tmp'; try { if (@file_put_contents($temporary, 'where('key', $key)->exists(); } }