Skip to content

Commit

Permalink
Fix CP-based clients not having their cache cleared when updated
Browse files Browse the repository at this point in the history
  • Loading branch information
engram-design committed Apr 20, 2023
1 parent 9f484a8 commit 6b4234a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/services/Clients.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\caching\TagDependency;

use Exception;
use Throwable;
Expand Down Expand Up @@ -289,6 +290,8 @@ public function saveClient(ClientInterface $client, bool $runValidation = true):

$client->afterSave($isNewClient);

TagDependency::invalidate(Craft::$app->getCache(), ['consume:' . $client->handle]);

// Fire an 'afterSaveClient' event
if ($this->hasEventHandlers(self::EVENT_AFTER_SAVE_CLIENT)) {
$this->trigger(self::EVENT_AFTER_SAVE_CLIENT, new ClientEvent([
Expand Down
13 changes: 12 additions & 1 deletion src/services/Service.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use DateTimeZone;
use Throwable;

use yii\caching\TagDependency;

use verbb\auth\helpers\UrlHelper as AuthUrlHelper;

use Symfony\Component\Serializer\Encoder\CsvEncoder;
Expand All @@ -37,6 +39,11 @@ public function fetchData(array|string $clientOpts, string $method = 'GET', stri
// Only cache if we've requested it, and probably just for GET requests. Seems odd to cache POST/DELETE/PUT.
if ($enableCache && $method === 'GET') {
$seconds = ConfigHelper::durationInSeconds($cacheDuration);
$cacheTags = ['consume'];

if (is_string($clientOpts)) {
$cacheTags[] = 'consume:' . $clientOpts;
}

// Generate a cache key based on all the provided data and duration (in case we change it)
$cacheKey = md5(Json::encode([$clientOpts, $method, $uri, $options, $seconds]));
Expand All @@ -49,7 +56,11 @@ public function fetchData(array|string $clientOpts, string $method = 'GET', stri

// Returning `false` ensures that the result is not cached, and evaluated next time
return false;
}, $seconds);
}, $seconds, new TagDependency([
// Allow us to tag the cache with the provider handle (and Consume in general) to make invalidating it easier when saving
// CP-based clients in the control panel when their settings change.
'tags' => $cacheTags,
]));

// Only return if we have a result
if ($cacheData) {
Expand Down

0 comments on commit 6b4234a

Please sign in to comment.