-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathFileHandler.php
More file actions
443 lines (369 loc) · 13.9 KB
/
Copy pathFileHandler.php
File metadata and controls
443 lines (369 loc) · 13.9 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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
<?php
declare(strict_types=1);
namespace CodeIgniter\Settings\Handlers;
use CodeIgniter\Settings\Config\Settings;
use RuntimeException;
/**
* Provides file-based persistence for Settings.
* Uses ArrayHandler for storage to minimize file I/O operations.
*/
class FileHandler extends ArrayHandler
{
/**
* Array of class+context combinations that have been loaded from disk.
* Format: ['ClassName::context', 'ClassName::null', ...]
*
* @var list<string>
*/
private array $hydrated = [];
/**
* Base path where settings files are stored.
*/
private readonly string $path;
private readonly Settings $config;
/**
* Stores the configured file path and ensures it exists.
*/
public function __construct()
{
$this->config = config('Settings');
$this->path = rtrim($this->config->file['path'] ?? WRITEPATH . 'settings', DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if (! is_dir($this->path) && (! mkdir($this->path, 0755, true) && ! is_dir($this->path))) {
throw new RuntimeException('Unable to create settings directory: ' . $this->path);
}
if (! is_writable($this->path)) {
throw new RuntimeException('Settings directory is not writable: ' . $this->path);
}
$this->setupDeferredWrites($this->config->file['deferWrites'] ?? false);
}
/**
* Checks whether this handler has a value set.
*/
public function has(string $class, string $property, ?string $context = null): bool
{
$this->hydrate($class, $context);
return $this->hasStored($class, $property, $context);
}
/**
* Attempt to retrieve a value from the file.
* To boost performance, all values are read and stored
* on the first call for each class+context, then retrieved from storage.
*
* @return mixed
*/
public function get(string $class, string $property, ?string $context = null)
{
$this->hydrate($class, $context);
return $this->getStored($class, $property, $context);
}
/**
* Stores values into a file for later retrieval.
*
* @param mixed $value
*
* @throws RuntimeException For file write failures
*/
public function set(string $class, string $property, $value = null, ?string $context = null): void
{
$this->hydrate($class, $context);
// Update in-memory storage first
$this->setStored($class, $property, $value, $context);
if ($this->deferWrites) {
$this->markPending($class, $property, $value, $context);
} else {
// For immediate writes, persist only this specific property change
$this->persist($class, $context, [[
'property' => $property,
'value' => $value,
'delete' => false,
]]);
}
}
/**
* Stores multiple values into files for later retrieval.
*
* @param list<array{class: string, property: string, value: mixed}> $settings
*
* @throws RuntimeException For file write failures
*/
public function setMany(array $settings, ?string $context = null): void
{
if ($settings === []) {
return;
}
$changesByClass = [];
foreach ($settings as $setting) {
$this->hydrate($setting['class'], $context);
$this->setStored($setting['class'], $setting['property'], $setting['value'], $context);
if ($this->deferWrites) {
$this->markPending($setting['class'], $setting['property'], $setting['value'], $context);
} else {
$changesByClass[$setting['class']][] = [
'property' => $setting['property'],
'value' => $setting['value'],
'delete' => false,
];
}
}
if ($this->deferWrites) {
return;
}
foreach ($changesByClass as $class => $changes) {
$this->persist($class, $context, $changes);
}
}
/**
* Deletes the record from persistent storage, if found,
* and from the local cache.
*
* @throws RuntimeException For file write failures
*/
public function forget(string $class, string $property, ?string $context = null): void
{
$this->hydrate($class, $context);
// Delete from local storage
$this->forgetStored($class, $property, $context);
if ($this->deferWrites) {
$this->markPending($class, $property, null, $context, true);
} else {
// For immediate writes, persist only this specific property deletion
$this->persist($class, $context, [[
'property' => $property,
'value' => null,
'delete' => true,
]]);
}
}
/**
* Deletes multiple records from persistent storage, if found,
* and from the local cache.
*
* @param list<array{class: string, property: string}> $settings
*
* @throws RuntimeException For file write failures
*/
public function forgetMany(array $settings, ?string $context = null): void
{
if ($settings === []) {
return;
}
$changesByClass = [];
foreach ($settings as $setting) {
$this->hydrate($setting['class'], $context);
$this->forgetStored($setting['class'], $setting['property'], $context);
if ($this->deferWrites) {
$this->markPending($setting['class'], $setting['property'], null, $context, true);
} else {
$changesByClass[$setting['class']][] = [
'property' => $setting['property'],
'value' => null,
'delete' => true,
];
}
}
if ($this->deferWrites) {
return;
}
foreach ($changesByClass as $class => $changes) {
$this->persist($class, $context, $changes);
}
}
/**
* Deletes all settings files from persistent storage
* and clears the local cache.
*
* @throws RuntimeException For file deletion failures
*/
public function flush(): void
{
// Delete all .php files in main directory (null context files)
$files = glob($this->path . '*.php', GLOB_NOSORT);
if ($files === false) {
throw new RuntimeException('Unable to read settings directory: ' . $this->path);
}
foreach ($files as $file) {
if (! unlink($file)) {
throw new RuntimeException('Unable to delete settings file: ' . $file);
}
}
// Delete all context subdirectories and their contents
$directories = glob($this->path . '*', GLOB_ONLYDIR | GLOB_NOSORT);
if ($directories !== false) {
foreach ($directories as $directory) {
// Delete all files inside the directory
$contextFiles = glob($directory . '/*.php', GLOB_NOSORT);
if ($contextFiles !== false) {
foreach ($contextFiles as $file) {
if (! unlink($file)) {
throw new RuntimeException('Unable to delete settings file: ' . $file);
}
}
}
// Remove the empty directory
if (! rmdir($directory)) {
throw new RuntimeException('Unable to delete directory: ' . $directory);
}
}
}
// Clear local storage and hydration tracking
parent::flush();
$this->hydrated = [];
}
/**
* Fetches values from files in bulk to minimize I/O operations.
* Loads all properties for a specific class+context combination.
*
* @throws RuntimeException For file read failures
*/
private function hydrate(string $class, ?string $context): void
{
$key = $this->getHydrationKey($class, $context);
// Check if already loaded
if (in_array($key, $this->hydrated, true)) {
return;
}
// Load the specific class+context file
$this->loadFromFile($class, $context);
$this->hydrated[] = $key;
// Also load general context for this class if not already loaded
if ($context !== null) {
$generalKey = $this->getHydrationKey($class, null);
if (! in_array($generalKey, $this->hydrated, true)) {
$this->loadFromFile($class, null);
$this->hydrated[] = $generalKey;
}
}
}
/**
* Loads settings from a file for a given class+context.
*
* @throws RuntimeException For file read failures
*/
private function loadFromFile(string $class, ?string $context): void
{
$filePath = $this->getFilePath($class, $context);
// If file doesn't exist, that's fine - no settings stored yet
if (! file_exists($filePath)) {
return;
}
// Use include to get the data array
$data = include $filePath;
if (! is_array($data)) {
throw new RuntimeException('Settings file does not return an array: ' . $filePath);
}
// Load data into in-memory storage
foreach ($data as $property => $valueData) {
if (! is_array($valueData) || ! isset($valueData['value'], $valueData['type'])) {
continue;
}
$this->setStored($class, $property, $this->parseValue($valueData['value'], $valueData['type']), $context);
}
}
/**
* Persists specific property changes to disk.
* Used for both immediate and deferred writes.
*
* @param list<array{property: string, value: mixed, delete: bool}> $changes Array of property changes to apply
*
* @throws RuntimeException For file write failures
*/
private function persist(string $class, ?string $context, array $changes): void
{
$filePath = $this->getFilePath($class, $context);
// Ensure directory exists (especially for context subdirectories)
$directory = dirname($filePath);
if (! is_dir($directory) && (! mkdir($directory, 0755, true) && ! is_dir($directory))) {
throw new RuntimeException('Unable to create directory: ' . $directory);
}
// Open/create file for locking
$lockHandle = fopen($filePath, 'c+b');
if ($lockHandle === false) {
throw new RuntimeException('Unable to open file for locking: ' . $filePath);
}
try {
// Acquire exclusive lock
if (! flock($lockHandle, LOCK_EX)) {
throw new RuntimeException('Unable to acquire lock on file: ' . $filePath);
}
// Clear file stat cache to get current file size
clearstatcache(true, $filePath);
$currentData = [];
if (filesize($filePath) > 0) {
$currentData = include $filePath;
if (! is_array($currentData)) {
$currentData = [];
}
}
// Apply all pending changes
foreach ($changes as $change) {
if ($change['delete']) {
// Explicitly delete this property
unset($currentData[$change['property']]);
} else {
// Set or update this property
$currentData[$change['property']] = [
'value' => $change['value'],
'type' => gettype($change['value']),
];
}
}
// Generate PHP file content
$content = '<?php' . PHP_EOL . PHP_EOL;
$content .= 'return ' . var_export($currentData, true) . ';' . PHP_EOL;
// Write file
if (file_put_contents($filePath, $content) === false) {
throw new RuntimeException('Unable to write settings file: ' . $filePath);
}
@chmod($filePath, 0644);
} finally {
flock($lockHandle, LOCK_UN);
fclose($lockHandle);
}
}
/**
* Persists all pending properties to disk.
* Called automatically at the end of request via post_system
* event when deferWrites is enabled.
*/
public function persistPendingProperties(): void
{
if ($this->pendingProperties === []) {
return;
}
// Group pending properties by class+context using parent helper
$grouped = $this->getPendingPropertiesGrouped();
// Persist each class+context group
foreach ($grouped as $group) {
try {
$this->persist($group['class'], $group['context'], $group['changes']);
} catch (RuntimeException $e) {
log_message('error', 'Failed to persist pending properties for ' . $group['class'] . ': ' . $e->getMessage());
}
}
$this->pendingProperties = [];
}
/**
* Generates a file path for a given class+context combination.
*
* Structure:
* - Null context: writable/settings/Class_Name.php
* - With context: writable/settings/{hash(context)}/Class_Name.php
*/
private function getFilePath(string $class, ?string $context): string
{
$className = str_replace('\\', '_', $class);
if ($context === null) {
return $this->path . $className . '.php';
}
$contextHash = hash('xxh128', $context);
return $this->path . $contextHash . DIRECTORY_SEPARATOR . $className . '.php';
}
/**
* Generates a hydration key for a class+context combination.
* Format: $class when context is null, $class::$context otherwise.
*/
private function getHydrationKey(string $class, ?string $context): string
{
return $context === null ? $class : $class . '::' . $context;
}
}