Last active
August 26, 2021 14:33
-
-
Save michaelhue/e7008e9f6689bbb5f52e7704745abc3e to your computer and use it in GitHub Desktop.
Craft CMS workaround for "resourcepaths" UPSERTs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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