Skip to content

Commit

Permalink
[5.x] Static cache response statuses (#10334)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonvarga authored Jun 19, 2024
1 parent 55f92fb commit 52f8508
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/StaticCaching/Middleware/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Statamic\StaticCaching\NoCache\RegionNotFound;
use Statamic\StaticCaching\NoCache\Session;
use Statamic\StaticCaching\Replacer;
use Statamic\StaticCaching\ResponseStatus;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\NoLock;
use Symfony\Component\Lock\Store\FlockStore;
Expand Down Expand Up @@ -99,6 +100,8 @@ private function attemptToGetCachedResponse($request)

$this->makeReplacements($response);

$response->setStaticCacheResponseStatus(ResponseStatus::HIT);

return $response;
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/StaticCaching/ResponseStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Statamic\StaticCaching;

enum ResponseStatus
{
case HIT;
case MISS;
case UNDEFINED;
}
31 changes: 31 additions & 0 deletions src/StaticCaching/ResponseStatusTracker.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Statamic\StaticCaching;

use Illuminate\Http\Response;

class ResponseStatusTracker
{
private array $responses = [];

public function set(Response $response, ResponseStatus $status): void
{
$this->responses[spl_object_id($response)] = $status;
}

public function get(Response $response): ResponseStatus
{
return $this->responses[spl_object_id($response)] ?? ResponseStatus::UNDEFINED;
}

public function registerMacros(): void
{
$tracker = $this;

Response::macro('setStaticCacheResponseStatus', fn ($status) => $tracker->set($this, $status));

Response::macro('staticCacheResponseStatus', fn () => $tracker->get($this));

Response::macro('wasStaticallyCached', fn () => $this->staticCacheResponseStatus() === ResponseStatus::HIT);
}
}
4 changes: 4 additions & 0 deletions src/StaticCaching/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ public function register()
$urls
);
});

$this->app->singleton(ResponseStatusTracker::class, fn () => new ResponseStatusTracker);
}

public function boot()
Expand All @@ -87,5 +89,7 @@ public function boot()

return $this;
});

$this->app[ResponseStatusTracker::class]->registerMacros();
}
}

0 comments on commit 52f8508

Please sign in to comment.