99
1010use Closure ;
1111use DateTimeInterface ;
12+ use LogicException ;
1213use Mantle \Cache \SWR_Storage ;
1314
1415use function Mantle \Support \Helpers \defer ;
@@ -46,24 +47,22 @@ public function __construct( protected int|\DateInterval|\DateTimeInterface $sta
4647 public function __invoke ( Pending_Request $ request , Closure $ next ): Response {
4748 $ this ->cache_key = $ this ->get_cache_key ( $ request );
4849
49- $ cache = wp_cache_get ( $ this ->cache_key , self :: CACHE_GROUP );
50+ $ cache = $ this ->get_cached_response ( );
5051
51- if ( $ cache && $ cache instanceof SWR_Storage ) {
52+ if ( $ cache instanceof SWR_Storage && $ cache-> value instanceof Response ) {
5253 $ response = $ cache ->value ;
5354
54- if ( $ response instanceof Response ) {
55- // If the cache is stale, we can still return it, but we should refresh
56- // deferred to the end of the request.
57- if ( $ cache ->is_stale () ) {
58- $ fresh_request = ( clone $ request )->without_middleware ( Cache_Middleware::class );
55+ // If the cache is stale, we can still return it, but we should refresh
56+ // deferred to the end of the request.
57+ if ( $ cache ->is_stale () ) {
58+ $ fresh_request = ( clone $ request )->without_middleware ( Cache_Middleware::class );
5959
60- defer ( fn () => $ this ->store_response ( $ fresh_request ->send () ) );
61- }
60+ defer ( fn () => $ this ->store_response ( $ fresh_request ->send () ) );
61+ }
6262
63- $ response ->cached = true ;
63+ $ response ->cached = true ;
6464
65- return $ response ;
66- }
65+ return $ response ;
6766 }
6867
6968 $ response = $ next ( $ request );
@@ -75,6 +74,25 @@ public function __invoke( Pending_Request $request, Closure $next ): Response {
7574 return $ response ;
7675 }
7776
77+ /**
78+ * Retrieve a cached response if available.
79+ *
80+ * @return SWR_Storage|null Cached response or null if not found.
81+ */
82+ private function get_cached_response (): ?SWR_Storage {
83+ try {
84+ $ cache = wp_cache_get ( $ this ->cache_key , self ::CACHE_GROUP );
85+
86+ if ( $ cache && $ cache instanceof SWR_Storage ) {
87+ return $ cache ;
88+ }
89+
90+ return null ;
91+ } catch ( LogicException ) {
92+ return null ;
93+ }
94+ }
95+
7896 /**
7997 * Store a response in the cache.
8098 *
0 commit comments