Skip to content

Commit

Permalink
Cache with preview domain
Browse files Browse the repository at this point in the history
  • Loading branch information
timkelty committed Nov 17, 2023
1 parent 52a7696 commit 4593ca4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
13 changes: 13 additions & 0 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Craft;
use craft\config\BaseConfig;
use craft\helpers\App;
use League\Uri\Uri;

/**
* @method array s3ClientOptions(array $options)
Expand All @@ -21,6 +22,7 @@ class Config extends BaseConfig
public ?string $accessSecret = null;
public ?string $cdnSigningKey = null;
public bool $useAssetBundleCdn = true;
public ?string $previewDomain = null;
protected ?string $region = null;
protected bool $useAssetCdn = true;
protected bool $useArtifactCdn = true;
Expand Down Expand Up @@ -124,6 +126,17 @@ public function getShortEnvironmentId(): ?string
: null;
}

public function getPreviewDomainUrl(): ?string
{
if (!$this->previewDomain) {
return null;
}

return (Uri::new())
->withHost($this->previewDomain)
->withScheme('https');
}

protected function defineRules(): array
{
$rules = parent::defineRules();
Expand Down
18 changes: 6 additions & 12 deletions src/StaticCaching.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
use craft\events\InvalidateElementCachesEvent;
use craft\events\RegisterCacheOptionsEvent;
use craft\events\TemplateEvent;
use craft\helpers\UrlHelper;
use craft\web\Response as WebResponse;
use craft\web\UrlManager;
use craft\web\View;
use Illuminate\Support\Collection;
use samdark\log\PsrMessage;
use yii\base\Exception;
use yii\caching\TagDependency;

class StaticCaching extends \yii\base\Component
Expand Down Expand Up @@ -76,21 +76,15 @@ public function handleRegisterCacheOptions(RegisterCacheOptionsEvent $event): vo
public function purgeAll(): void
{
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.',
]);
$url = Module::getInstance()->getConfig()->getPreviewDomainUrl();

throw new \yii\console\Exception($message);
if (!$url) {
throw new Exception('Unable to purge cache from the CLI without a preview domain.');
}

// TODO: should this hit a ping/healthcheck controller instead?
Craft::createGuzzleClient()
->request('HEAD', (string) $url, [
->request('HEAD', $url, [
'headers' => [
HeaderEnum::CACHE_PURGE->value => '*',
],
Expand Down

0 comments on commit 4593ca4

Please sign in to comment.