|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * This file is part of CodeIgniter 4 framework. |
| 7 | + * |
| 8 | + * (c) CodeIgniter Foundation <admin@codeigniter.com> |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view |
| 11 | + * the LICENSE file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace CodeIgniter\Router\Attributes; |
| 15 | + |
| 16 | +use Attribute; |
| 17 | +use CodeIgniter\HTTP\RequestInterface; |
| 18 | +use CodeIgniter\HTTP\ResponseInterface; |
| 19 | + |
| 20 | +/** |
| 21 | + * Cache Attribute |
| 22 | + * |
| 23 | + * Caches the response of a controller method at the server level for a specified duration. |
| 24 | + * This is server-side caching to avoid expensive operations, not browser-level caching. |
| 25 | + * |
| 26 | + * Usage: |
| 27 | + * ```php |
| 28 | + * #[Cache(for: 3600)] // Cache for 1 hour |
| 29 | + * #[Cache(for: 300, key: 'custom_key')] // Cache with custom key |
| 30 | + * ``` |
| 31 | + * |
| 32 | + * Limitations: |
| 33 | + * - Only caches GET requests; POST, PUT, DELETE, and other methods are ignored |
| 34 | + * - Streaming responses or file downloads may not cache properly |
| 35 | + * - Cache key includes HTTP method, path, query string, and possibly user_id(), but not request headers |
| 36 | + * - Does not automatically invalidate related cache entries |
| 37 | + * - Cookies set in the response are cached and reused for all subsequent requests |
| 38 | + * - Large responses may impact cache storage performance |
| 39 | + * - Browser Cache-Control headers do not affect server-side caching behavior |
| 40 | + * |
| 41 | + * Security Considerations: |
| 42 | + * - Ensure cache backend is properly secured and not accessible publicly |
| 43 | + * - Be aware that authorization checks happen before cache lookup |
| 44 | + */ |
| 45 | +#[Attribute(Attribute::TARGET_METHOD)] |
| 46 | +class Cache implements RouteAttributeInterface |
| 47 | +{ |
| 48 | + public function __construct( |
| 49 | + public int $for = 3600, |
| 50 | + public ?string $key = null, |
| 51 | + ) { |
| 52 | + } |
| 53 | + |
| 54 | + public function before(RequestInterface $request): RequestInterface|ResponseInterface|null |
| 55 | + { |
| 56 | + // Only cache GET requests |
| 57 | + if ($request->getMethod() !== 'GET') { |
| 58 | + return null; |
| 59 | + } |
| 60 | + |
| 61 | + // Check cache before controller execution |
| 62 | + $cacheKey = $this->key ?? $this->generateCacheKey($request); |
| 63 | + |
| 64 | + $cached = cache($cacheKey); |
| 65 | + // Validate cached data structure |
| 66 | + if ($cached !== null && (is_array($cached) && isset($cached['body'], $cached['headers'], $cached['status']))) { |
| 67 | + $response = service('response'); |
| 68 | + $response->setBody($cached['body']); |
| 69 | + $response->setStatusCode($cached['status']); |
| 70 | + // Mark response as served from cache to prevent re-caching |
| 71 | + $response->setHeader('X-Cached-Response', 'true'); |
| 72 | + |
| 73 | + // Restore headers from cached array of header name => value strings |
| 74 | + foreach ($cached['headers'] as $name => $value) { |
| 75 | + $response->setHeader($name, $value); |
| 76 | + } |
| 77 | + $response->setHeader('Age', (string) (time() - ($cached['timestamp'] ?? time()))); |
| 78 | + |
| 79 | + return $response; |
| 80 | + } |
| 81 | + |
| 82 | + return null; // Continue to controller |
| 83 | + } |
| 84 | + |
| 85 | + public function after(RequestInterface $request, ResponseInterface $response): ?ResponseInterface |
| 86 | + { |
| 87 | + // Don't re-cache if response was already served from cache |
| 88 | + if ($response->hasHeader('X-Cached-Response')) { |
| 89 | + // Remove the marker header before sending response |
| 90 | + $response->removeHeader('X-Cached-Response'); |
| 91 | + |
| 92 | + return null; |
| 93 | + } |
| 94 | + |
| 95 | + // Only cache GET requests |
| 96 | + if ($request->getMethod() !== 'GET') { |
| 97 | + return null; |
| 98 | + } |
| 99 | + |
| 100 | + $cacheKey = $this->key ?? $this->generateCacheKey($request); |
| 101 | + |
| 102 | + // Convert Header objects to strings for caching |
| 103 | + $headers = []; |
| 104 | + |
| 105 | + foreach ($response->headers() as $name => $header) { |
| 106 | + // Handle both single Header and array of Headers |
| 107 | + if (is_array($header)) { |
| 108 | + // Multiple headers with same name |
| 109 | + $values = []; |
| 110 | + |
| 111 | + foreach ($header as $h) { |
| 112 | + $values[] = $h->getValueLine(); |
| 113 | + } |
| 114 | + $headers[$name] = implode(', ', $values); |
| 115 | + } else { |
| 116 | + // Single header |
| 117 | + $headers[$name] = $header->getValueLine(); |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + $data = [ |
| 122 | + 'body' => $response->getBody(), |
| 123 | + 'headers' => $headers, |
| 124 | + 'status' => $response->getStatusCode(), |
| 125 | + 'timestamp' => time(), |
| 126 | + ]; |
| 127 | + |
| 128 | + cache()->save($cacheKey, $data, $this->for); |
| 129 | + |
| 130 | + return $response; |
| 131 | + } |
| 132 | + |
| 133 | + protected function generateCacheKey(RequestInterface $request): string |
| 134 | + { |
| 135 | + return 'route_cache_' . hash( |
| 136 | + 'xxh128', |
| 137 | + $request->getMethod() . |
| 138 | + $request->getUri()->getPath() . |
| 139 | + $request->getUri()->getQuery() . |
| 140 | + (function_exists('user_id') ? user_id() : ''), |
| 141 | + ); |
| 142 | + } |
| 143 | +} |
0 commit comments