AbstractSettingsDictionary.php
11.5 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<?php
namespace YahnisElsts\AdminMenuEditor\Customizable\Storage;
use ameMultiDictionary;
use YahnisElsts\AdminMenuEditor\Customizable\Builders\ElementBuilderFactory;
use YahnisElsts\AdminMenuEditor\Customizable\Builders\SettingFactory;
use YahnisElsts\AdminMenuEditor\Customizable\Settings\AbstractSetting;
use YahnisElsts\AdminMenuEditor\Customizable\Settings\PredefinedSet;
use YahnisElsts\AdminMenuEditor\Customizable\Settings\Setting;
use YahnisElsts\AdminMenuEditor\Customizable\Settings\SettingGeneratorInterface;
use YahnisElsts\AdminMenuEditor\Customizable\Settings\StringSetting;
/**
* What's the difference between this and StorageInterface? A StorageInterface just
* reads and writes data. It doesn't know what the data is, how it's organized, or
* how to validate it.
*
* This class, on the other hand, is dictionary (or associative array) with string keys,
* potentially multidimensional. It can have predefined defaults, and it can create
* Setting instances for its keys.
*/
abstract class AbstractSettingsDictionary implements \ArrayAccess, \JsonSerializable {
/**
* @var array
*/
protected $defaults;
/**
* @var StorageInterface
*/
protected $store;
/**
* @var null|AbstractSetting[]
*/
protected $registeredSettings = null;
/**
* @var null|\YahnisElsts\AdminMenuEditor\Customizable\Settings\PredefinedSet[]
*/
protected $registeredSets = null;
/**
* @var string Optional ID prefix that can be added to setting IDs
* to make them globally unique.
*/
protected $idPrefix;
/**
* @var object
*/
protected $undefinedMarker;
/**
* @var bool Whether to automatically track the last modification time.
*/
protected $lastModifiedTimeEnabled = false;
/**
* @var null|Setting
*/
protected $lastModifiedSetting = null;
const LAST_MODIFIED_KEY = '_lastModified';
public function __construct(StorageInterface $store, $idPrefix = '', $lastModifiedTimeEnabled = false) {
$this->store = $store;
$this->idPrefix = $idPrefix;
$this->lastModifiedTimeEnabled = $lastModifiedTimeEnabled;
$this->defaults = $this->createDefaults();
$this->undefinedMarker = new \StdClass();
}
/**
* @return array<string,mixed>
*/
abstract protected function createDefaults();
/**
* @return array<string,Setting> Settings indexed by their ID.
*/
abstract protected function createSettings();
/**
* Get the value of a setting.
*
* Note that NULLs are treated as valid values. The fallback value will only
* be used if the setting is actually missing, not if it's set to NULL.
*
* @param string|string[] $path
* @param mixed $fallback
* @return mixed
*/
public function get($path, $fallback = null) {
//Try the storage.
$result = $this->store->getPath($path, $this->undefinedMarker);
if ( $result !== $this->undefinedMarker ) {
return $result;
}
//Try predefined defaults.
return $this->getDefault($path, $fallback);
}
public function set($path, $value) {
$this->store->setPath($path, $value);
}
/**
* @param string $path
* @param mixed $fallback
* @return mixed
*/
protected function getDefault($path, $fallback = null) {
return ameMultiDictionary::get($this->defaults, $path, $fallback);
}
/**
* @return array<string,AbstractSetting>
*/
public function getRegisteredSettings() {
if ( $this->registeredSettings === null ) {
$this->populateSettingInstances();
}
return $this->registeredSettings;
}
/**
* @return array<string,PredefinedSet>
*/
public function getRegisteredSets() {
if ( $this->registeredSets === null ) {
$this->populateSettingInstances();
}
return $this->registeredSets;
}
private function populateSettingInstances() {
list($this->registeredSettings, $this->registeredSets)
= $this->flattenSettingsCollection($this->createSettings());
if ( $this->lastModifiedTimeEnabled ) {
$settingsWithoutLastModified = $this->registeredSettings;
$path = self::LAST_MODIFIED_KEY;
$this->lastModifiedSetting = new StringSetting(
$this->idPrefix . $path,
$this->store->buildSlot($path),
[]
);
$this->registeredSettings[$this->lastModifiedSetting->getId()] = $this->lastModifiedSetting;
AbstractSetting::subscribeDeferred($settingsWithoutLastModified, function () {
$this->lastModifiedSetting->update(gmdate('c'));
});
}
}
/**
* Flatten a collection of settings and index it by ID.
*
* Also detects predefined sets present in the collection and adds them
* to a separate array indexed by ID.
*
* @param array|\Traversable $settings
* @return array{0: array<string,AbstractSetting>, 1: array<string,PredefinedSet>}
*/
private function flattenSettingsCollection($settings) {
$foundSettings = [];
$foundSets = [];
$this->addSettingsToCollection($foundSettings, $foundSets, $settings);
return [$foundSettings, $foundSets];
}
/**
* @param array $outputCollection
* @param array $detectedSets
* @param array|\Traversable $inputCollection
* @return void
*/
private function addSettingsToCollection(&$outputCollection, &$detectedSets, $inputCollection) {
foreach ($inputCollection as $item) {
if ( empty($item) ) {
continue;
}
if ( $item instanceof PredefinedSet ) {
$detectedSets[$item->getId()] = $item;
}
if ( $item instanceof AbstractSetting ) {
$outputCollection[$item->getId()] = $item;
} else if ( is_array($item) || ($item instanceof SettingGeneratorInterface) ) {
$this->addSettingsToCollection($outputCollection, $detectedSets, $item);
} else {
throw new \InvalidArgumentException(
'Unexpected item type in a setting collection: '
. is_object($item) ? get_class($item) : gettype($item)
);
}
}
}
/**
* Like findSetting(), but throws an exception if the setting doesn't exist.
*
* @param string $settingIdOrPath
* @return AbstractSetting
*/
public function getSetting($settingIdOrPath) {
$result = $this->findSetting($settingIdOrPath);
if ( $result !== null ) {
return $result;
}
throw new \InvalidArgumentException("Unknown setting: $settingIdOrPath");
}
/**
* Find a setting by ID or path.
*
* @param $settingIdOrPath
* @return AbstractSetting|null
*/
public function findSetting($settingIdOrPath) {
$settings = $this->getRegisteredSettings();
//Try the plain ID.
/** @noinspection PhpRedundantOptionalArgumentInspection */
$result = ameMultiDictionary::get($settings, $settingIdOrPath, null);
if ( $result !== null ) {
return $result;
}
//Try the ID with the prefix.
if ( !empty($this->idPrefix) && is_string($settingIdOrPath) ) {
/** @noinspection PhpRedundantOptionalArgumentInspection */
$result = ameMultiDictionary::get($settings, $this->idPrefix . $settingIdOrPath, null);
if ( $result !== null ) {
return $result;
}
}
return null;
}
/**
* @param string $setIdOrPath
* @return PredefinedSet
*/
public function getPredefinedSet($setIdOrPath) {
if ( isset($this->registeredSets[$setIdOrPath]) ) {
return $this->registeredSets[$setIdOrPath];
}
if ( !empty($this->idPrefix) ) {
$idWithPrefix = $this->idPrefix . $setIdOrPath;
if ( isset($this->registeredSets[$idWithPrefix]) ) {
return $this->registeredSets[$idWithPrefix];
}
}
$setting = ameMultiDictionary::get($this->getRegisteredSettings(), $setIdOrPath);
if ( $setting instanceof PredefinedSet ) {
return $setting;
}
throw new \InvalidArgumentException("Unknown set: $setIdOrPath");
}
/**
* Get the default values of all registered settings (recursive).
*
* Note: The intent is to return the defaults in a format that can be safely
* JSON-encoded and passed to JavaScript. This means that empty associative
* arrays and structs are converted to empty objects.
*
* @return array<string,mixed> A map of setting IDs to their default values.
*/
public function getRecursiveDefaultsForJs() {
//Generate a map of all supported settings and their defaults.
$settings = $this->getRegisteredSettings();
$defaults = [];
foreach (AbstractSetting::recursivelyIterateSettings($settings) as $setting) {
$defaultValue = $setting->getDefaultValue();
//wp_json_encode() encodes empty associative arrays as plain JS arrays,
//but we need empty objects. We can't distinguish between an empty associative
//array and a normal array, so we also need to check the setting's data type.
if ( is_array($defaultValue) && empty($defaultValue) && ($setting->getDataType() === 'map') ) {
$defaultValue = new \stdClass();
}
$defaults[$setting->getId()] = $defaultValue;
}
return $defaults;
}
public function save() {
$this->store->save();
}
/**
* @param array<string,string|string[]> $aliases
* @return void
*/
public function addReadAliases($aliases) {
$this->store->addReadAliases($aliases);
}
/**
* Merge the elements of this setting collection and an associative array.
*
* This is not a recursive merge. The input array will simply overwrite any
* settings that have the same keys.
*
* @param array $newSettings
* @return void
*/
public function mergeWith($newSettings) {
$oldSettings = $this->toArray();
$this->store->setValue(array_merge($oldSettings, $newSettings));
}
/**
* @noinspection PhpLanguageLevelInspection
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset) {
return $this->get($offset);
}
/**
* @noinspection PhpLanguageLevelInspection
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value) {
$this->set($offset, $value);
}
/**
* @noinspection PhpLanguageLevelInspection
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset) {
$this->store->deletePath($offset);
}
/**
* @noinspection PhpLanguageLevelInspection
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset) {
/*
* Caution: This implementation breaks the implied contract for NULL values.
* PHP seems to assume that offsetExists() will return false when the offset
* exists but the value is NULL. For example, isset() doesn't bother calling
* offsetGet() to check the actual value when offsetExists() returns true.
*
* This version may return true instead (depending on the underlying storage
* implementation).
*
* Unlike isset(), empty() still works correctly.
*/
return ($this->get($offset, $this->undefinedMarker) !== $this->undefinedMarker);
}
/** @noinspection PhpLanguageLevelInspection */
#[\ReturnTypeWillChange]
public function jsonSerialize() {
$data = $this->store->getValue();
if ( empty($data) ) {
//Usually, json_encode() will serialize an empty array as "[]", but
//we want "{}" in case it gets used in JavaScript.
return new \StdClass();
}
return $data;
}
public function toArray() {
$value = $this->store->getValue();
if ( empty($value) ) {
return array();
}
return (array)$value;
}
/**
* Does this collection have custom values for any settings?
*
* A true result does not necessarily mean that the custom values are different
* from the defaults, only that some settings have been set/changed.
*
* @return bool
*/
public function hasCustomValues() {
$data = $this->store->getValue();
return !empty($data);
}
/**
* @return int|null
*/
public function getLastModifiedTimestamp() {
if ( !$this->lastModifiedTimeEnabled ) {
return null;
}
$isoTimestamp = $this->get(self::LAST_MODIFIED_KEY);
if ( empty($isoTimestamp) ) {
return null;
}
return strtotime($isoTimestamp);
}
public function elementBuilder() {
return new ElementBuilderFactory($this);
}
public function settingFactory() {
return new SettingFactory($this->store, $this->defaults, $this->idPrefix);
}
}