You are here

function core_views_facets_entity_presave in Core Views 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.

Throws

\Drupal\Core\Entity\EntityStorageException In case of failures an exception is thrown.

File

./core_views_facets.module, line 71
Contains core_views_facets.module.

Code

function core_views_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".
        foreach ([
          'core_views_contextual_filter:',
          'core_views_exposed_filter:',
        ] as $facet_source) {
          $facets_source_plugin_id = $facet_source . $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 ($source_entity !== NULL) {
              $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();
    }
  }
}