Repository navigation
Expand file tree
/
Copy pathSettings.php
More file actions
305 lines (264 loc) · 11.1 KB
/
Copy pathSettings.php
File metadata and controls
305 lines (264 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
<?php
declare(strict_types=1);
namespace NyonCode\WireModuleSettings\Support;
use Illuminate\Contracts\Cache\Repository;
use Illuminate\Support\Facades\Cache;
use NyonCode\WireModuleSettings\Contracts\SpansSettingsGroups;
use NyonCode\WireModuleSettings\Events\SettingsSaved;
use NyonCode\WireModuleSettings\Models\Setting;
/**
* Read and write application settings.
*
* A settings value is read on nearly every request and written almost never, so
* the whole group is cached as one entry and the cache is dropped on write. Per
* key would be one lookup per read; per group is one for a page that reads six.
*
* **Reads never touch the database when the table is not there.** A settings
* call sits in application code that also runs during `migrate` and in a fresh
* install, and a missing table must answer the default rather than throw — which
* is what makes `Settings::get()` safe to put in a config-like place.
*
* **A missing table is never cached, though**, and that is the difference
* between the sentence above being true and being true once. `rememberForever`
* stores whatever the callback returned, so the empty array a pre-migration read
* produced was written into the cache and answered every read afterwards — a
* fresh install whose deploy touched a setting before `migrate` came up with
* every value empty and stayed that way until something wrote one. The table
* check now short-circuits *before* the store is written to.
*
* **A declared default is a value.** {@see ProvidesSettingsDefaults} lets a
* group say what its values are before anybody sets them, and those come back
* from `get()` and `all()` under whatever is stored — so the default lives in
* the group rather than being repeated at every call site, where five of the six
* copies agree.
*/
final class Settings
{
private const CACHE_PREFIX = 'wire-settings.';
/**
* One value: stored, else declared by the group, else what the caller named.
*/
public static function get(string $key, mixed $default = null, string $group = 'general'): mixed
{
$values = self::all($group);
return array_key_exists($key, $values) ? $values[$key] : $default;
}
/** Whether anything is stored under this key — a declared default is not. */
public static function has(string $key, string $group = 'general'): bool
{
return array_key_exists($key, self::stored($group));
}
/**
* Every value in a group, keyed: the group's declared defaults with whatever
* is stored written over them.
*
* @return array<string, mixed>
*/
public static function all(string $group = 'general'): array
{
return [...SettingsGroups::defaultsFor($group), ...self::stored($group)];
}
public static function set(string $key, mixed $value, string $group = 'general'): void
{
self::fill([$key => $value], $group);
}
/**
* Write a whole group at once — what a settings form does on save.
*
* **One transaction**, which is the promise the settings screen is built on:
* it edits one group at a time so it never has to say "your branding saved
* but your mail did not", and a loop of six writes where the fourth fails
* says exactly that about one group's own fields. All of it lands or none
* of it does.
*
* The cache is dropped after the transaction rather than inside it. The
* model drops it too, on every write (see {@see Setting::booted()}) — that
* is the guard for a value changed from a seeder or from tinker — but a
* forget that happens mid-transaction can be followed by a read that caches
* the pre-commit rows again, so the one that matters is this one.
*
* @param array<string, mixed> $values
*/
public static function fill(array $values, string $group = 'general'): void
{
self::fillMany([$group => $values]);
}
/**
* Write several groups at once, in one transaction.
*
* For a screen that edits one thing stored in more than one group
* ({@see SpansSettingsGroups}): two
* {@see fill()} calls would be two transactions, and the second failing
* would leave the first written — exactly the "half of it saved" this class
* promises a screen never has to explain. Each group's cache is dropped and
* each group is announced on its own afterwards, the same as {@see fill()}
* does for one; a group with nothing in it is neither.
*
* @param array<string, array<string, mixed>> $groups Values by storage group.
*/
public static function fillMany(array $groups): void
{
$groups = array_filter($groups, static fn (array $values): bool => $values !== []);
if ($groups === []) {
return;
}
Setting::query()->getConnection()->transaction(static function () use ($groups): void {
foreach ($groups as $group => $values) {
foreach ($values as $key => $value) {
Setting::query()->updateOrCreate(
['group' => (string) $group, 'key' => (string) $key],
['value' => $value],
);
}
}
});
foreach ($groups as $group => $values) {
self::forget((string) $group);
event(new SettingsSaved((string) $group, $values));
}
}
/**
* Remove one stored value, so the group's declared default answers again.
*
* Announced as a {@see SettingsSaved}, because to anything listening it is
* one: the value that answers for this key changed. A listener that rebuilds
* a mail transport when the `mail` group is written has to hear the custom
* host being removed just as much as being set — before, it heard only the
* second, and mail kept going to the removed server until something else
* wrote to the group. Nothing is announced when nothing was stored.
*/
public static function remove(string $key, string $group = 'general'): void
{
$removed = Setting::query()->where('group', $group)->where('key', $key)->delete();
self::forget($group);
if ($removed > 0) {
self::announceRemoved([$key], $group);
}
}
/** Remove everything stored for a group, announced as {@see remove()} is. */
public static function clear(string $group = 'general'): void
{
$keys = Setting::query()->where('group', $group)->pluck('key')->all();
Setting::query()->where('group', $group)->delete();
self::forget($group);
if ($keys !== []) {
self::announceRemoved($keys, $group);
}
}
/**
* Tell listeners what now answers for keys that were removed.
*
* The group's declared default where it has one, `null` where it does not —
* which is exactly what {@see get()} answers from here on, so a listener
* reading `$event->values` and one calling `Settings::all()` agree.
*
* @param array<int, string> $keys
*/
private static function announceRemoved(array $keys, string $group): void
{
$defaults = SettingsGroups::defaultsFor($group);
$values = [];
foreach ($keys as $key) {
$values[$key] = $defaults[$key] ?? null;
}
event(new SettingsSaved($group, $values));
}
/**
* Drop a group's cached values, leaving what is stored alone.
*
* **Call it after a write the model did not make.** A group is cached for
* ever and dropped by the model's own events, so a query-builder write —
* `Setting::query()->update()`, a `DB::table()` insert in a data migration,
* a `truncate()` — changes the rows and leaves every worker answering the
* old values until something clears them. That is what this is for.
*/
public static function forget(string $group = 'general'): void
{
self::cache()->forget(self::CACHE_PREFIX.$group);
}
/**
* What is actually in the table for a group, cached.
*
* Separate from {@see all()} so the cache holds stored rows and nothing else:
* a declared default merged in here would be frozen into the store, and
* changing it in the group class would then take a cache clear to be seen.
*
* @return array<string, mixed>
*/
private static function stored(string $group): array
{
if (! self::caching()) {
return self::tableExists() ? self::read($group) : [];
}
$cache = self::cache();
$cached = $cache->get(self::CACHE_PREFIX.$group);
if (is_array($cached)) {
return $cached;
}
// Answered, and deliberately not written to the store: a read before
// `migrate` must not be the answer this application gives afterwards.
if (! self::tableExists()) {
return [];
}
$values = self::read($group);
$cache->forever(self::CACHE_PREFIX.$group, $values);
return $values;
}
/** @return array<string, mixed> */
private static function read(string $group): array
{
return Setting::query()
->where('group', $group)
->pluck('value', 'key')
->all();
}
/**
* The store settings are cached in.
*
* Configurable because the default store is the wrong one often enough to
* matter: settings are read on nearly every request, and a `database` store
* turns the one query this class exists to avoid into a different one. An
* application on Redis names it here and the read stops touching the
* database at all.
*/
private static function cache(): Repository
{
return Cache::store(self::cacheStore());
}
/**
* The store `wire-module-settings.cache.store` names, or null for the
* application's default.
*
* Blank is null: `WIRE_SETTINGS_CACHE_STORE=` arrives as an empty string, and
* the installer and `about` used to read that as a store literally named "".
*/
public static function cacheStore(): ?string
{
$store = config('wire-module-settings.cache.store');
return is_string($store) && trim($store) !== '' ? trim($store) : null;
}
/** The store settings are actually cached in, default included. */
public static function effectiveCacheStore(): string
{
return self::cacheStore() ?? (string) config('cache.default', 'file');
}
private static function caching(): bool
{
return (bool) config('wire-module-settings.cache.enabled', true);
}
/**
* Whether the table is there at all.
*
* Called only on a cache miss, so it costs one schema query per group per
* cache lifetime rather than one per read. Deliberately **not** memoised in
* a static: under Octane a static outlives the request, so an application
* that migrated after its first read would keep answering "no table" until
* the worker was restarted.
*/
private static function tableExists(): bool
{
return Setting::query()->getConnection()
->getSchemaBuilder()
->hasTable((new Setting)->getTable());
}
}