Skip to content

Commit

Permalink
Merge pull request #14 from craftcms/feature/cld-369-add-static-cache…
Browse files Browse the repository at this point in the history
…-clearing-utility

Cache purge tag by host
  • Loading branch information
timkelty authored Nov 17, 2023
2 parents 69e0098 + 21e1408 commit c97cd71
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
3 changes: 1 addition & 2 deletions src/HeaderEnum.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
enum HeaderEnum: string
{
case CACHE_TAG = 'Cache-Tag';
case CACHE_PURGE_TAG = 'Cache-Purge-Tag';
case CACHE_PURGE_HOST = 'Cache-Purge-Host';
case CACHE_PURGE = 'Cache-Purge';
case CACHE_CONTROL = 'Cache-Control';
}
22 changes: 15 additions & 7 deletions src/StaticCaching.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
use craft\web\UrlManager;
use craft\web\View;
use Illuminate\Support\Collection;
use League\Uri\Uri;
use samdark\log\PsrMessage;
use yii\caching\TagDependency;

Expand Down Expand Up @@ -76,15 +75,24 @@ public function handleRegisterCacheOptions(RegisterCacheOptionsEvent $event): vo

public function purgeAll(): void
{
if (Craft::$app->getRequest()->isConsoleRequest) {
$url = Uri::new(UrlHelper::baseSiteUrl());
if (Craft::$app->getRequest()->getIsConsoleRequest()) {
// TODO: should this hit a ping/healthcheck controller instead?
$url = UrlHelper::baseSiteUrl();

if (str_starts_with($url, '@web')) {
$message = implode(PHP_EOL, [
'Unable to clear static caches because the web host isn\'t known for console commands.',
'Explicitly set the @web alias in config/general.php to avoid this error.',
'See https://craftcms.com/docs/4.x/config/#aliases for more info.',
]);

// TODO: warn about @web not being defined for CLI
throw new \yii\console\Exception($message);
}

Craft::createGuzzleClient()
->request('HEAD', (string) $url, [
'headers' => [
HeaderEnum::CACHE_PURGE_HOST->value => '*',
HeaderEnum::CACHE_PURGE->value => '*',
],
]);

Expand All @@ -93,7 +101,7 @@ public function purgeAll(): void


Craft::$app->getResponse()->getHeaders()->set(
HeaderEnum::CACHE_PURGE_HOST->value, '*',
HeaderEnum::CACHE_PURGE->value, '*',
);
}

Expand Down Expand Up @@ -195,7 +203,7 @@ protected function addCachePurgeTagsToResponse(array $tags): void
$headers = Craft::$app->getResponse()->getHeaders();

$tagsForHeader->each(fn(string $tag) => $headers->add(
HeaderEnum::CACHE_PURGE_TAG->value,
HeaderEnum::CACHE_PURGE->value,
$tag,
));
}
Expand Down
2 changes: 1 addition & 1 deletion src/web/ResponseBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function init(): void
{
$this->csvHeaders = [
HeaderEnum::CACHE_TAG->value,
HeaderEnum::CACHE_PURGE_TAG->value,
HeaderEnum::CACHE_PURGE->value,
];
}

Expand Down

0 comments on commit c97cd71

Please sign in to comment.