1414namespace RegexParser \Cache ;
1515
1616use Psr \Cache \CacheItemPoolInterface ;
17+ use RegexParser \Node \RegexNode ;
1718
1819/**
1920 * PSR-6 bridge for AST caching.
2021 *
21- * Uses the configured pool to store serialized AST payloads.
22+ * This adapter lets you plug a PSR-6 cache pool into the RegexParser cache
23+ * system. The Regex service passes a compiled cache payload string
24+ * (generated by {@see \RegexParser\Regex::compileCachePayload()}); this
25+ * adapter evaluates that payload once and stores the resulting RegexNode
26+ * instance directly in the pool so that subsequent reads are fast and
27+ * type-safe.
2228 */
2329final readonly class PsrCacheAdapter implements RemovableCacheInterface
2430{
@@ -42,7 +48,10 @@ public function generateKey(string $regex): string
4248 public function write (string $ key , string $ content ): void
4349 {
4450 $ item = $ this ->pool ->getItem ($ key );
45- $ item ->set ($ content );
51+
52+ $ value = $ this ->decodePayload ($ content );
53+ $ item ->set ($ value ?? $ content );
54+
4655 $ this ->pool ->save ($ item );
4756 }
4857
@@ -69,4 +78,31 @@ public function clear(?string $regex = null): void
6978
7079 $ this ->pool ->clear ();
7180 }
81+
82+ /**
83+ * Decodes the compiled cache payload string into a RegexNode instance.
84+ *
85+ * The Regex service passes a small PHP script generated by
86+ * {@see \RegexParser\Regex::compileCachePayload()}. For PSR-6 caches we
87+ * execute this script once and store the resulting AST object directly
88+ * in the pool so that subsequent reads return a RegexNode instead of
89+ * the raw payload string.
90+ */
91+ private function decodePayload (string $ content ): ?RegexNode
92+ {
93+ $ code = ltrim ($ content );
94+
95+ if (str_starts_with ($ code , '<?php ' )) {
96+ $ code = substr ($ code , 5 );
97+ }
98+
99+ try {
100+ $ result = eval ($ code );
101+
102+ return $ result instanceof RegexNode ? $ result : null ;
103+ } catch (\Throwable ) {
104+ // If anything goes wrong we just fall back to storing the raw payload.
105+ return null ;
106+ }
107+ }
72108}
0 commit comments