From 99640093465fd15a54e66d5ad3650a2ec4a06473 Mon Sep 17 00:00:00 2001 From: Brad Jorsch Date: Thu, 30 Nov 2017 13:52:30 -0500 Subject: [PATCH] Cache processed stylesheets during the parse If we've already processed a stylesheet once, there's no point in processing it again. Change-Id: I83f7aab82cc7674037974b0de43ccae6c77ff39f --- TemplateStylesHooks.php | 38 ++++++++++++++++++++++++++++++++++---- extension.json | 3 +++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/TemplateStylesHooks.php b/TemplateStylesHooks.php index 4742cab..5587a46 100644 --- a/TemplateStylesHooks.php +++ b/TemplateStylesHooks.php @@ -126,6 +126,7 @@ class TemplateStylesHooks { */ public static function onParserFirstCallInit( &$parser ) { $parser->setHook( 'templatestyles', 'TemplateStylesHooks::handleTag' ); + $parser->extTemplateStylesCache = new MapCacheLRU( 100 ); // 100 is arbitrary return true; } @@ -178,6 +179,14 @@ class TemplateStylesHooks { return true; } + /** + * Clear our cache when the parser is reset + * @param Parser $parser + */ + public static function onParserClearState( Parser $parser ) { + $parser->extTemplateStylesCache->clear(); + } + /** * Parser hook for `` * @param string $text Contents of the tag (ignored). @@ -235,13 +244,32 @@ class TemplateStylesHooks { ''; } - // For the moment just output the styles inline. - // @todo: If T160563 happens, it would be good to convert this to use that. + // If the revision actually has an ID, cache based on that. + // Otherwise, cache by hash. + if ( $rev->getId() ) { + $cacheKey = 'r' . $rev->getId(); + } else { + $cacheKey = sha1( $content->getNativeData() ); + } + + // Include any non-default wrapper class in the cache key too + $wrapClass = $parser->getOptions()->getWrapOutputClass(); + if ( $wrapClass === false ) { + $wrapClass = 'mw-parser-output'; + } + if ( $wrapClass !== 'mw-parser-output' ) { + $cacheKey .= '/' . $wrapClass; + } + + // Already cached? + if ( $parser->extTemplateStylesCache->has( $cacheKey ) ) { + return $parser->extTemplateStylesCache->get( $cacheKey ); + } $status = $content->sanitize( [ 'flip' => $parser->getTargetLanguage()->getDir() !== $wgContLang->getDir(), 'minify' => !ResourceLoader::inDebugMode(), - 'class' => $parser->getOptions()->getWrapOutputClass(), + 'class' => $wrapClass, ] ); $style = $status->isOk() ? $status->getValue() : '/* Fatal error, no CSS will be output */'; @@ -270,7 +298,9 @@ class TemplateStylesHooks { // Return the inline