1 | <?php |
||
2 | |||
3 | namespace LeKoala\DebugBar\Proxy; |
||
4 | |||
5 | use LeKoala\DebugBar\Collector\PartialCacheCollector; |
||
6 | use SilverStripe\Core\Convert; |
||
7 | use Symfony\Component\Cache\Psr16Cache; |
||
8 | |||
9 | class CacheProxy extends Psr16Cache |
||
10 | { |
||
11 | public const string CONTEXT_TMP = '__TEMP__'; |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
12 | |||
13 | protected static $data = []; |
||
14 | |||
15 | protected string $context = ''; |
||
16 | |||
17 | public function setContext(string $context): self |
||
18 | { |
||
19 | $this->context = $context; |
||
20 | |||
21 | return $this; |
||
22 | } |
||
23 | |||
24 | public function set($key, $value, $ttl = null): bool |
||
25 | { |
||
26 | self::$data[__FUNCTION__ . $key] = [ |
||
27 | "key" => $key, |
||
28 | "type" => __FUNCTION__, |
||
29 | "value" => $value, |
||
30 | "ttl" => $ttl, |
||
31 | "caller" => $this->getCaller(), |
||
32 | ]; |
||
33 | return parent::set($key, $value, $ttl); |
||
34 | } |
||
35 | |||
36 | public function get($key, $default = null): mixed |
||
37 | { |
||
38 | $value = parent::get($key, $default); |
||
39 | |||
40 | if ($this->context === self::CONTEXT_TMP) { |
||
41 | $message = (empty((string)$value)) ? "Missed: {$key}" : "Hit: {$key}"; |
||
42 | $result = preg_replace('/\s+/', ' ', trim($value ?? '')); |
||
43 | $result = Convert::raw2att($result); |
||
44 | |||
45 | PartialCacheCollector::addTemplateCache( |
||
46 | $message, |
||
47 | [ |
||
48 | 'cache_result' => |
||
49 | ['result' => $result] |
||
50 | ] |
||
51 | ); |
||
52 | } |
||
53 | |||
54 | self::$data[__FUNCTION__ . $key] = [ |
||
55 | "key" => $key, |
||
56 | "type" => __FUNCTION__, |
||
57 | "value" => $value, |
||
58 | "caller" => $this->getCaller(), |
||
59 | ]; |
||
60 | return $value; |
||
61 | } |
||
62 | |||
63 | private function getCaller(): string |
||
64 | { |
||
65 | $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); |
||
66 | $caller = ""; |
||
67 | $ignore = ["set", "get", "setCacheValue", "getCacheValue", "getCaller"]; |
||
68 | foreach ($trace as $t) { |
||
69 | if (in_array($t['function'], $ignore)) { |
||
70 | continue; |
||
71 | } |
||
72 | if (isset($t['file'])) { |
||
73 | $caller = basename($t['file']) . ':' . $t['line']; |
||
74 | } elseif (isset($t['class'])) { |
||
75 | $caller = $t['class']; |
||
76 | } |
||
77 | break; |
||
78 | } |
||
79 | return $caller; |
||
80 | } |
||
81 | |||
82 | public static function getData(): array |
||
83 | { |
||
84 | return self::$data; |
||
85 | } |
||
86 | } |
||
87 |