You are here

function facets_entity_presave in Facets 8

Implements hook_entity_presave().

We implement this to make sure that a facet gets removed on view updates, so we don't get broken facet blocks.

File

./facets.module, line 79
Contains facets.module.

Code

function facets_entity_presave(EntityInterface $entity) {

  // Make sure that we only react on view entities with changed displays.
  if ($entity instanceof View && !empty($entity->original)) {
    if ($entity->original
      ->get('display') != $entity
      ->get('display')) {

      /** @var \Drupal\facets\FacetSource\FacetSourcePluginManager $facet_source_plugin_manager */
      $facet_source_plugin_manager = \Drupal::getContainer()
        ->get('plugin.manager.facets.facet_source');
      $definitions = $facet_source_plugin_manager
        ->getDefinitions();

      // Setup an array of sources that are deleted.
      $sources = [];
      foreach ($entity->original
        ->get('display') as $k => $display) {

        // Check if the current display is also a facet source plugin and that
        // is removed from the view. We use the double underscore here to make
        // sure that we use core convention of "plugin:derived_plugin".
        $facets_source_plugin_id = 'search_api:views_' . $display['display_plugin'] . '__' . $entity
          ->id() . '__' . $display['id'];
        if (array_key_exists($facets_source_plugin_id, $definitions) && !array_key_exists($k, $entity
          ->get('display'))) {
          $entity_id = str_replace(':', '__', $facets_source_plugin_id);
          $source_entity = FacetSource::load($entity_id);
          $sources[] = $facets_source_plugin_id;
          if (!is_null($source_entity)) {
            $source_entity
              ->delete();
          }
        }
      }

      // Loop over all deleted sources and delete the facets that were linked to
      // that source.
      if (count($sources) > 0) {

        /** @var \Drupal\facets\FacetManager\DefaultFacetManager $fm */
        $fm = \Drupal::getContainer()
          ->get('facets.manager');
        foreach ($sources as $source) {
          $facets = $fm
            ->getFacetsByFacetSourceId($source);
          foreach ($facets as $facet) {
            $facet
              ->delete();
          }
        }
      }
      $facet_source_plugin_manager
        ->clearCachedDefinitions();
    }
  }
}