Skip to content

Instantly share code, notes, and snippets.

@michaelhue
Last active August 26, 2021 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelhue/e7008e9f6689bbb5f52e7704745abc3e to your computer and use it in GitHub Desktop.
Save michaelhue/e7008e9f6689bbb5f52e7704745abc3e to your computer and use it in GitHub Desktop.
Craft CMS workaround for "resourcepaths" UPSERTs
<?php
use craft\events\RegisterCacheOptionsEvent;
use craft\utilities\ClearCaches;
use yii\base\Event;
// Register the "resourcepaths" cache tag for clearing via craft command.
// Important: the following command should be run after every deploy.
// php craft invalidate-tags/resourcepaths
Event::on(
ClearCaches::class,
ClearCaches::EVENT_REGISTER_TAG_OPTIONS,
function (RegisterCacheOptionsEvent $event): void {
$event->options[] = [
"tag" => "resourcepaths",
"label" => Craft::t("app", "Asset resource paths"),
];
}
);
return [
// ...
'components' => [
'assetManager' => function () {
$config = craft\helpers\App::assetManagerConfig();
$manager = Craft::createObject($config);
// Use a cache tag to allow invalidating the cache.
$cacheTag = new \yii\caching\TagDependency(['tags' => 'resourcepaths']);
// Add a custom hash callback which prevents the UPSERT query.
$manager->hashCallback = function ($path) use ($manager, $cacheTag) {
$dir = is_file($path) ? dirname($path) : $path;
$alias = Craft::alias($dir);
$linkAssets = $manager->linkAssets;
return Craft::$app->getCache()->getOrSet(
$alias,
function () use ($path, $alias, $linkAssets) {
// Use the original method for generating the hash.
$modified = \craft\helpers\FileHelper::lastModifiedTime($path);
$hash = sprintf('%x', crc32("$alias|$modified|$linkAssets"));
// Keep the original upsert for backwards compatibility.
try {
\craft\helpers\Db::upsert(
\craft\db\Table::RESOURCEPATHS,
['hash' => $hash],
['path' => $alias],
[],
false
);
} catch (\Exception $e) {
// ignore
}
return $hash;
},
0,
$cacheTag
);
};
return $manager;
},
],
// ...
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment