This repository was archived by the owner on Feb 17, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCompiledCache.php
More file actions
490 lines (417 loc) · 14.4 KB
/
CompiledCache.php
File metadata and controls
490 lines (417 loc) · 14.4 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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<?php
declare(strict_types=1);
namespace AttributeRegistry\Service;
use AttributeRegistry\Enum\AttributeTargetType;
use AttributeRegistry\ValueObject\AttributeInfo;
use AttributeRegistry\ValueObject\AttributeTarget;
use Brick\VarExporter\VarExporter;
use Cake\Log\Log;
use Closure;
use RuntimeException;
use Throwable;
/**
* Compiled cache service for zero-cost attribute caching.
*
* Generates executable PHP files that directly instantiate AttributeInfo objects,
* leveraging OPcache for maximum performance with zero hydration overhead.
*/
class CompiledCache
{
private readonly string $cachePath;
/**
* @var array<string, array<\AttributeRegistry\ValueObject\AttributeInfo>> In-memory cache
*/
private array $memoryCache = [];
/**
* Constructor for CompiledCache.
*
* @param string $cachePath Path to store compiled cache files (will be normalized with trailing separator)
* @param bool $enabled Whether caching is enabled
* @param bool $validateFiles Whether to validate file modification times on cache retrieval (development mode)
*/
public function __construct(
string $cachePath,
private readonly bool $enabled = true,
private readonly bool $validateFiles = false,
) {
// Ensure cachePath ends with directory separator
if ($cachePath !== '' && !str_ends_with($cachePath, DIRECTORY_SEPARATOR)) {
$cachePath .= DIRECTORY_SEPARATOR;
}
$this->cachePath = $cachePath;
}
/**
* Check if caching is enabled.
*
* @return bool Whether caching is enabled
*/
public function isEnabled(): bool
{
return $this->enabled;
}
/**
* Check if file validation is enabled.
*
* @return bool Whether file validation is enabled
*/
public function isValidationEnabled(): bool
{
return $this->validateFiles;
}
/**
* Get cached data by key.
*
* @param string $key Cache key
* @return array<\AttributeRegistry\ValueObject\AttributeInfo>|null Cached data or null if not found
*/
public function get(string $key): ?array
{
if (!$this->enabled) {
return null;
}
// Check in-memory cache first (skip if validation is enabled to ensure fresh validation)
if (!$this->validateFiles && isset($this->memoryCache[$key])) {
return $this->memoryCache[$key];
}
$filePath = $this->getCacheFilePath($key);
if (!file_exists($filePath)) {
return null;
}
try {
$data = require $filePath;
if (is_array($data)) {
// Validate file hashes if enabled
if ($this->validateFiles && $data !== []) {
$validated = $this->validateCachedData($data);
if ($validated === null) {
// Validation failed, cache is stale
return null;
}
$data = $validated;
}
// Only cache in memory if validation is disabled (to ensure fresh validation on each get)
if (!$this->validateFiles) {
$this->memoryCache[$key] = $data;
}
return $data;
}
return null;
} catch (Throwable $throwable) {
Log::error('Failed to load compiled cache: ' . $throwable->getMessage());
return null;
}
}
/**
* Set data in cache.
*
* @param string $key Cache key
* @param array<\AttributeRegistry\ValueObject\AttributeInfo> $data Data to cache
* @return bool Success status
*/
public function set(string $key, array $data): bool
{
if (!$this->enabled) {
return false;
}
try {
// Validate all items
foreach ($data as $item) {
if (!$item instanceof AttributeInfo) {
throw new RuntimeException('Data must contain AttributeInfo objects');
}
$this->validateAttributeInfo($item);
}
$code = $this->generateCompiledCode($data);
$filePath = $this->getCacheFilePath($key);
$result = $this->atomicWrite($filePath, $code);
if ($result) {
// Update in-memory cache
$this->memoryCache[$key] = $data;
}
return $result;
} catch (Throwable $throwable) {
Log::error('Failed to write compiled cache: ' . $throwable->getMessage());
return false;
}
}
/**
* Delete cached data by key.
*
* @param string $key Cache key
* @return bool Success status
*/
public function delete(string $key): bool
{
if (!$this->enabled) {
return false;
}
// Clear from memory cache
if (isset($this->memoryCache[$key])) {
unset($this->memoryCache[$key]);
}
$filePath = $this->getCacheFilePath($key);
if (!file_exists($filePath)) {
return true; // Nothing to delete is success
}
// Invalidate OPcache before deleting
if (function_exists('opcache_invalidate')) {
@opcache_invalidate($filePath, true); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
}
return @unlink($filePath); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
}
/**
* Clear all cached data.
*
* @return bool Success status
*/
public function clear(): bool
{
if (!$this->enabled) {
return false;
}
// Clear memory cache
$this->memoryCache = [];
if (!is_dir($this->cachePath)) {
return true;
}
$files = glob($this->cachePath . '*.php');
if ($files === false) {
return false;
}
foreach ($files as $file) {
// Invalidate OPcache before deleting
if (function_exists('opcache_invalidate')) {
@opcache_invalidate($file, true); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
}
@unlink($file); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
}
return true;
}
/**
* Generate compiled PHP code from AttributeInfo array.
*
* @param array<\AttributeRegistry\ValueObject\AttributeInfo> $attributeInfos Attributes to compile
* @return string Generated PHP code
*/
private function generateCompiledCode(array $attributeInfos): string
{
$items = array_map(
fn(AttributeInfo $attr): string => $this->generateAttributeInfo($attr),
$attributeInfos,
);
return $this->buildFileContent($items, count($attributeInfos));
}
/**
* Generate code for a single AttributeInfo instance.
*
* @param \AttributeRegistry\ValueObject\AttributeInfo $attr Attribute to generate code for
* @return string Generated code
*/
private function generateAttributeInfo(AttributeInfo $attr): string
{
$indent = ' ';
return sprintf(
"%snew \\AttributeRegistry\\ValueObject\\AttributeInfo(\n" .
"%s className: %s,\n" .
"%s attributeName: %s,\n" .
"%s arguments: %s,\n" .
"%s filePath: %s,\n" .
"%s lineNumber: %d,\n" .
"%s target: %s,\n" .
"%s fileTime: %d,\n" .
"%s pluginName: %s,\n" .
'%s)',
$indent,
$indent,
VarExporter::export($attr->className),
$indent,
VarExporter::export($attr->attributeName),
$indent,
VarExporter::export($attr->arguments, indentLevel: 2),
$indent,
VarExporter::export($attr->filePath),
$indent,
$attr->lineNumber,
$indent,
$this->generateAttributeTarget($attr->target, 2),
$indent,
$attr->fileTime,
$indent,
$attr->pluginName === null ? 'null' : VarExporter::export($attr->pluginName),
$indent,
);
}
/**
* Generate code for an AttributeTarget instance.
*
* @param \AttributeRegistry\ValueObject\AttributeTarget $target Target to generate code for
* @param int $level Indentation level
* @return string Generated code
*/
private function generateAttributeTarget(AttributeTarget $target, int $level): string
{
$indent = str_repeat(' ', $level);
$innerIndent = str_repeat(' ', $level + 1);
return sprintf(
"new \\AttributeRegistry\\ValueObject\\AttributeTarget(\n" .
'%stype: ' . AttributeTargetType::class . '::%s,' . "\n" .
"%stargetName: %s,\n" .
"%sparentClass: %s,\n" .
'%s)',
$innerIndent,
$target->type->name,
$innerIndent,
VarExporter::export($target->targetName),
$innerIndent,
VarExporter::export($target->parentClass, indentLevel: $level),
$indent,
);
}
/**
* Build complete file content with header and metadata.
*
* @param array<string> $items Generated attribute items
* @param int $count Number of attributes
* @return string Complete PHP file content
*/
private function buildFileContent(array $items, int $count): string
{
$timestamp = date('Y-m-d H:i:s');
$itemsCode = $items === [] ? '' : "\n" . implode(",\n\n", $items) . ",\n";
return <<<PHP
<?php
// phpcs:ignoreFile
/**
* Pre-compiled Attribute Registry Cache
*
* Generated: {$timestamp}
* Attributes: {$count}
*
* DO NOT EDIT THIS FILE MANUALLY
* Regenerate with: bin/cake attribute discover
*/
declare(strict_types=1);
return [{$itemsCode}];
PHP;
}
/**
* Write content to file atomically.
*
* @param string $filePath Target file path
* @param string $content Content to write
* @return bool Success status
*/
private function atomicWrite(string $filePath, string $content): bool
{
$dir = dirname($filePath);
// Ensure directory exists
if (!is_dir($dir) && (!mkdir($dir, 0755, true) && !is_dir($dir))) {
return false;
}
// Write to temporary file first
$tempFile = $filePath . '.' . uniqid('tmp', true);
try {
if (file_put_contents($tempFile, $content, LOCK_EX) === false) {
return false;
}
// Set permissions - log warning if it fails but continue
if (!chmod($tempFile, 0644)) {
Log::warning('Failed to chmod cache file: ' . $tempFile);
}
// Atomic rename
if (!rename($tempFile, $filePath)) {
@unlink($tempFile); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
return false;
}
// Clear OPcache for this file
if (function_exists('opcache_invalidate')) {
opcache_invalidate($filePath, true);
}
return true;
} catch (Throwable $throwable) {
@unlink($tempFile); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
return false;
}
}
/**
* Get cache file path for a key.
*
* @param string $key Cache key
* @return string File path
*/
private function getCacheFilePath(string $key): string
{
// Sanitize key for filesystem
$safeKey = preg_replace('/[^a-z0-9_-]/i', '_', $key);
return $this->cachePath . $safeKey . '.php';
}
/**
* Validate an AttributeInfo object for exportability.
*
* @param \AttributeRegistry\ValueObject\AttributeInfo $attr Attribute to validate
* @throws \RuntimeException If attribute contains non-exportable values
*/
private function validateAttributeInfo(AttributeInfo $attr): void
{
// Check arguments for non-exportable types
$this->validateValue($attr->arguments, 'arguments');
}
/**
* Validate a value for exportability.
*
* @param mixed $value Value to validate
* @param string $context Context for error messages
* @throws \RuntimeException If value is not exportable
*/
private function validateValue(mixed $value, string $context): void
{
if (is_resource($value)) {
throw new RuntimeException('Cannot export attribute with resource in ' . $context);
}
if ($value instanceof Closure) {
throw new RuntimeException('Cannot export attribute with closure in ' . $context);
}
if (is_array($value)) {
foreach ($value as $key => $item) {
$this->validateValue($item, sprintf('%s[%s]', $context, $key));
}
}
// VarExporter handles all other types including objects
}
/**
* Validate cached data by checking file modification times.
*
* Returns null if any files have changed (cache is stale).
*
* @param array<\AttributeRegistry\ValueObject\AttributeInfo> $data Cached attribute data
* @return array<\AttributeRegistry\ValueObject\AttributeInfo>|null Validated data or null if stale
*/
private function validateCachedData(array $data): ?array
{
// Cache file modification times to avoid redundant reads when multiple attributes come from the same file
$fileTimeCache = [];
foreach ($data as $attr) {
// Check if file still exists
if (!file_exists($attr->filePath)) {
return null;
}
// Get modification time from cache or compute it
if (!isset($fileTimeCache[$attr->filePath])) {
$currentTime = filemtime($attr->filePath);
if ($currentTime === false) {
Log::warning(sprintf(
'Failed to get modification time for file "%s" while validating cached data.',
$attr->filePath,
));
return null;
}
$fileTimeCache[$attr->filePath] = $currentTime;
}
if ($fileTimeCache[$attr->filePath] !== $attr->fileTime) {
// File has changed, cache is stale
return null;
}
}
return $data;
}
}