diff --git a/src/Entity/Facet.php b/src/Entity/Facet.php index 7a9f165..b658234 100644 --- a/src/Entity/Facet.php +++ b/src/Entity/Facet.php @@ -1062,8 +1062,8 @@ class Facet extends ConfigEntityBase implements FacetInterface { parent::postSave($storage, $update); if (!$update) { self::clearBlockCache(); - // Register newly inserted facet within its source. - if (!$this->isSyncing() && $source = $this->getFacetSource()) { + // Register newly created facet within its source, for the caching. + if (($source = $this->getFacetSource()) && $source->getCacheMaxAge() !== 0) { $source->registerFacet($this); } } diff --git a/src/Plugin/facets/facet_source/SearchApiDisplay.php b/src/Plugin/facets/facet_source/SearchApiDisplay.php index 8b5fa57..a6d5080 100644 --- a/src/Plugin/facets/facet_source/SearchApiDisplay.php +++ b/src/Plugin/facets/facet_source/SearchApiDisplay.php @@ -32,6 +32,14 @@ use Symfony\Component\HttpFoundation\Request; */ class SearchApiDisplay extends FacetSourcePluginBase implements SearchApiFacetSourceInterface { + /** + * List of Search API cache plugins that works with Facets cache system. + */ + const CACHEABLE_PLUGINS = [ + 'search_api_tag', + 'search_api_time', + ]; + /** * The search index the query should is executed on. * @@ -453,13 +461,31 @@ class SearchApiDisplay extends FacetSourcePluginBase implements SearchApiFacetSo } /** - * {@inheritdoc} + * {@inheritDoc} + * + * Alter views view cache metadata: + * - When view being re-saved it will collect all cache metadata from its + * plugins, including cache plugin. + * - Search API cache plugin will pre-execute the query and collect cacheable + * metadata from all facets and will pass it to the view. + * + * View will use collected cache tags to invalidate search results. And cache + * context provided by the facet to vary results. + * + * @see \Drupal\views\Plugin\views\display\DisplayPluginBase::calculateCacheMetadata() + * @see \Drupal\search_api\Plugin\views\cache\SearchApiCachePluginTrait::alterCacheMetadata() + * @see \Drupal\facets\FacetManager\DefaultFacetManager::alterQuery() */ public function registerFacet(FacetInterface $facet) { - // Alter views view cache metadata. - // @see \Drupal\search_api\Plugin\views\cache\SearchApiCachePluginTrait::generateResultsKey() - // @see \Drupal\views\Plugin\views\cache\CachePluginBase::alterCacheMetadata() - $this->getViewsDisplay()->save(); + if ( + // On the config-sync or site install view will already have all required + // cache tags, so don't react if it's already there. + !in_array('config:' . $facet->getConfigDependencyName(), $this->getCacheTags()) + // Re-save it only if we know that views cache plugin works with facets. + && in_array($this->getViewsDisplay()->getDisplay()->getOption('cache')['type'], static::CACHEABLE_PLUGINS) + ) { + $this->getViewsDisplay()->save(); + } } }