facets.module 16.7 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains facets.module.
6 7
 */

8
use Drupal\Component\Utility\Html;
9
use Drupal\Core\Breadcrumb\Breadcrumb;
10
use Drupal\Core\Form\FormStateInterface;
11
use Drupal\Core\Language\LanguageInterface;
12
use Drupal\Core\Link;
13
use Drupal\Core\Routing\RouteMatchInterface;
14
use Drupal\Core\Url;
15
use Drupal\facets\Entity\Facet;
16
use Drupal\facets\Entity\FacetSource;
17
use Drupal\facets\FacetInterface;
Nick_vh's avatar
Nick_vh committed
18
use Drupal\search_api\Query\QueryInterface;
19
use Drupal\views\Entity\View;
20
use Drupal\Core\Entity\EntityInterface;
21
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
22
use Drupal\Core\Logger\RfcLogLevel;
23 24 25 26

/**
 * Implements hook_help().
 */
27
function facets_help($route_name, RouteMatchInterface $route_match) {
28
  switch ($route_name) {
29 30
    // Main module help for the facets module.
    case 'help.page.facets':
31 32
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
33
      $output .= '<p>' . t('Facets test') . '</p>';
34
      return $output;
35

36
    case 'entity.facets_facet.collection':
37 38
      $output = '';
      $output .= '<p>' . t('Below is a list of facets grouped by facetsources they are associated with. A facetsource is the instance where the facet does the actual filtering, for example a View on a Search API index.') . '</p>';
39
      $output .= '<p>' . t('The facets weight can be changed with drag and drop within the same facet source. Although you can drag and drop a facet under any facet source, this change will not be performed on save.') . '</p>';
40
      return $output;
41 42 43
  }
}

44 45 46 47 48
/**
 * Implements hook_theme().
 */
function facets_theme($existing, $type, $theme, $path) {
  return [
49 50
    'facets_result_item' => [
      'variables' => [
51 52
        'facet' => NULL,
        'raw_value' => '',
53 54 55 56 57 58 59 60
        'value' => '',
        'show_count' => FALSE,
        'count' => NULL,
        'is_active' => FALSE,
      ],
    ],
    'facets_item_list' => [
      'variables' => [
61
        'facet' => NULL,
62 63 64 65 66 67 68 69 70
        'items' => [],
        'title' => '',
        'list_type' => 'ul',
        'wrapper_attributes' => [],
        'attributes' => [],
        'empty' => NULL,
        'context' => [],
      ],
    ],
71 72 73
  ];
}

Nick_vh's avatar
Nick_vh committed
74
/**
75
 * Implements hook_search_api_query_alter().
Nick_vh's avatar
Nick_vh committed
76
 */
77
function facets_search_api_query_alter(QueryInterface &$query) {
78 79 80
  if ($query->getIndex()->getServerInstance()->supportsFeature('search_api_facets')) {
    /** @var \Drupal\facets\FacetManager\DefaultFacetManager $facet_manager */
    $facet_manager = \Drupal::service('facets.manager');
Nick_vh's avatar
Nick_vh committed
81

82 83 84 85 86
    // It's safe to hardcode this to the search api scheme because this is in a
    // search_api_query_alter method. If this generated source is not correct,
    // implementing the same alter and directly calling
    // $manager->alterQuery($query, $your_facetsource_id); will fix that.
    $facet_source = 'search_api:' . str_replace(':', '__', $query->getSearchId());
Nick_vh's avatar
Nick_vh committed
87

88
    // Add the active filters.
89
    $facet_manager->alterQuery($query, $facet_source);
90
  }
Nick_vh's avatar
Nick_vh committed
91
}
92 93 94 95 96 97 98

/**
 * 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.
 */
99
function facets_entity_presave(EntityInterface $entity) {
100 101 102 103 104 105 106 107 108 109 110 111 112
  // 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
113 114
        // is removed from the view. We use the double underscore here to make
        // sure that we use core convention of "plugin:derived_plugin".
115
        $facets_source_plugin_id = 'search_api:views_' . $display['display_plugin'] . '__' . $entity->id() . '__' . $display['id'];
116 117
        if (array_key_exists($facets_source_plugin_id, $definitions) && !array_key_exists($k, $entity->get('display'))) {
          $entity_id = str_replace(':', '__', $facets_source_plugin_id);
118
          $source_entity = FacetSource::load($entity_id);
119
          $sources[] = $facets_source_plugin_id;
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
          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();
    }
  }

}
143 144 145 146 147 148 149 150 151

/**
 * Implements hook_preprocess_block().
 *
 * Adds a class for the widget to the facet block to allow for more specific
 * styling.
 */
function facets_preprocess_block(&$variables) {
  if ($variables['configuration']['provider'] == 'facets') {
152 153 154 155 156 157
    // Hide the block if it's empty.
    if (!empty($variables['elements']['content'][0]['#attributes']['class']) && in_array('facet-hidden', $variables['elements']['content'][0]['#attributes']['class'])) {
      // Add the Drupal class for hiding this for everyone, including screen
      // readers. See hidden.module.css in the core system module.
      $variables['attributes']['class'][] = 'hidden';
    }
158 159 160 161
    if (!empty($variables['derivative_plugin_id'])) {
      $facet = Facet::load($variables['derivative_plugin_id']);
      $variables['attributes']['class'][] = 'block-facet--' . Html::cleanCssIdentifier($facet->getWidget()['type']);
    }
162 163
  }
}
164 165 166 167 168 169 170 171

/**
 * Implements hook_entity_predelete().
 *
 * We implement this hook to make sure that facet source plugins are cleared
 * when a view is deleted. It also deletes facets that are created on those
 * plugins.
 */
172
function facets_entity_predelete(EntityInterface $entity) {
173 174 175 176 177
  if ($entity instanceof View) {
    $facet_source_plugin_manager = \Drupal::getContainer()
      ->get('plugin.manager.facets.facet_source');

    $definitions = $facet_source_plugin_manager->getDefinitions();
178

179 180 181
    if (!is_array($definitions)) {
      return;
    }
182

183
    foreach ($definitions as $plugin_id => $definition) {
184
      if (strpos($plugin_id, 'search_api:' . $entity->id() . '__') !== FALSE) {
185 186
        try {
          $facetManager = \Drupal::getContainer()->get('facets.manager');
187 188
        }
        catch (ServiceNotFoundException $e) {
189
          \Drupal::logger('facets')->log(RfcLogLevel::DEBUG, 'Facet manager not found on trying to delete a view.');
190 191
          return;
        }
192

193 194 195 196 197 198 199 200 201 202 203 204
        $facets = $facetManager->getFacetsByFacetSourceId($plugin_id);
        foreach ($facets as $facet) {
          $facet->delete();
        }
      }
    }

    // Clear cached plugin definitions for facet source to make sure we don't
    // show stale data.
    $facet_source_plugin_manager->clearCachedDefinitions();
  }
}
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

/**
 * Prepares variables for facets item list templates.
 *
 * Default template: facets-item-list.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - items: An array of items to be displayed in the list. Each item can be
 *     either a string or a render array. If #type, #theme, or #markup
 *     properties are not specified for child render arrays, they will be
 *     inherited from the parent list, allowing callers to specify larger
 *     nested lists without having to explicitly specify and repeat the
 *     render properties for all nested child lists.
 *   - title: A title to be prepended to the list.
 *   - list_type: The type of list to return (e.g. "ul", "ol").
 *   - wrapper_attributes: HTML attributes to be applied to the list wrapper.
 *
 * @see https://www.drupal.org/node/1842756
 */
225
function facets_preprocess_facets_item_list(array &$variables) {
226 227 228
  if ($variables['facet'] !== NULL && $variables['facet']->get('show_title') === TRUE) {
    $variables['title'] = $variables['facet']->label();
  }
229 230
  template_preprocess_item_list($variables);
}
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249

/**
 * Implements hook_system_breadcrumb_alter().
 */
function facets_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  /** @var \Drupal\facets\FacetSource\FacetSourcePluginManager $facet_source_manager */
  $facet_source_manager = \Drupal::service('plugin.manager.facets.facet_source');

  /** @var \Drupal\facets\FacetManager\DefaultFacetManager $facet_manager */
  $facet_manager = \Drupal::service('facets.manager');

  /** @var \Drupal\Core\Entity\EntityTypeManager $entity_type_manager */
  $entity_type_manager = \Drupal::service('entity_type.manager');

  /** @var \Drupal\Core\Entity\EntityStorageInterface $facet_source_storage */
  $facet_source_storage = $entity_type_manager->getStorage('facets_facet_source');

  $facet_sources_definitions = $facet_source_manager->getDefinitions();

250 251
  $facets_url_generator = \Drupal::service('facets.utility.url_generator');

252 253 254 255 256 257 258
  // No facet sources found, so don't do anything.
  if (empty($facet_sources_definitions)) {
    return;
  }

  foreach ($facet_sources_definitions as $definition) {
    /* @var \Drupal\facets\FacetSource\FacetSourcePluginBase $facet_source_plugin */
259 260
    $facetsource_id = $definition['id'];
    $facet_source_plugin = $facet_source_manager->createInstance($facetsource_id);
261 262 263 264 265 266 267

    // If the current facet source is not being rendered, don't do anything with
    // these facet sources.
    if (!$facet_source_plugin->isRenderedInCurrentRequest()) {
      continue;
    }

268
    $source_id = str_replace(':', '__', $facetsource_id);
269 270 271 272 273
    /** @var \Drupal\facets\FacetSourceInterface $facet_source */
    $facet_source = $facet_source_storage->load($source_id);

    // If the facet source is not loaded, or the facet source doesn't have
    // breadcrumbs enabled, don't do anything.
274
    if (!($facet_source && !empty($facet_source->getBreadcrumbSettings()['active']))) {
275 276 277 278 279 280 281 282
      continue;
    }

    // Add the required cacheability metadata.
    $breadcrumb->addCacheContexts(['url']);
    $breadcrumb->addCacheableDependency($facet_source);

    // Process the facets if they are not already processed.
283 284
    $facet_manager->processFacets($facetsource_id);
    $facets = $facet_manager->getFacetsByFacetSourceId($facetsource_id);
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300

    // Sort facets by weight.
    uasort($facets, function (FacetInterface $a, FacetInterface $b) {
      if ($a->getWeight() == $b->getWeight()) {
        return 0;
      }
      return ($a->getWeight() < $b->getWeight()) ? -1 : 1;
    });

    /** @var \Drupal\facets\UrlProcessor\UrlProcessorPluginManager $url_processor_manager */
    $url_processor_manager = \Drupal::service('plugin.manager.facets.url_processor');

    // Get active facets and results to use them at building the crumbs.
    $active_results = [];
    $active_facets = [];
    foreach ($facets as $facet) {
301
      if (count($facet->getActiveItems()) > 0) {
302 303 304 305 306 307 308
        // Add the facet as a cacheable dependency.
        $breadcrumb->addCacheableDependency($facet);
        /** @var \Drupal\facets\UrlProcessor\UrlProcessorInterface $url_processor */
        $url_processor = $url_processor_manager->createInstance($facet_source->getUrlProcessorName(), ['facet' => $facet]);
        $facet_manager->build($facet);

        foreach ($facet->getResults() as $result) {
309
          if ($result->isActive() || $result->hasActiveChildren()) {
310 311 312 313
            // Clone the result so we can mark it as inactive to be added to the
            // url parameters when calling buildUrls.
            $cloned_result = clone $result;
            $cloned_result->setActiveState(FALSE);
314
            $active_results[$facet->id()][] = $cloned_result;
315 316
          }
        }
317 318 319
        if (!empty($active_results[$facet->getUrlAlias()])) {
          $url_processor->buildUrls($facet, $active_results[$facet->getUrlAlias()]);
        }
320
        $active_facets[$facet->id()] = $facet;
321 322 323 324 325 326 327 328
      }
    }

    // TODO find a better way to construct the url for a crumb maybe url
    // processor will have a function to get params for a result
    // without all the other request parameters; with this we could implement:
    // @see https://www.drupal.org/node/2861586
    // TODO handle not grouped facets.
329
    /** @var \Drupal\facets\Result\ResultInterface[] $facet_results */
330 331
    foreach ($active_results as $facet_id => $facet_results) {
      $facet_used_result[$facet_id] = [];
332 333
      $facet_crumb_items = [];

334 335 336
      // Because we can't get the desired display value trough a url processor
      // method we iterate each result url and remove the facet params that
      // haven't been used on previous crumbs.
337
      foreach ($facet_results as $res) {
338
        $facet_used_result[$facet_id][] = $res->getRawValue();
339 340 341
        $facet_crumb_items[] = $res->getDisplayValue();
      }

342 343
      sort($facet_crumb_items);

344
      $facet_url = $facets_url_generator->getUrl($facet_used_result, FALSE);
345
      if (!empty($facet_source->getBreadcrumbSettings()['before'])) {
346
        $crumb_text = $active_facets[$facet_id]->label() . ': ' . implode(', ', $facet_crumb_items);
347 348 349 350
      }
      else {
        $crumb_text = implode(', ', $facet_crumb_items);
      };
351 352 353 354 355
      $link = Link::fromTextAndUrl($crumb_text, $facet_url);
      $breadcrumb->addLink($link);
    }
  }
}
356 357

/**
358
 * Implements hook_language_switch_links_alter().
359
 */
360
function facets_language_switch_links_alter(array &$links, $type, Url $url) {
361 362 363 364 365 366 367 368 369 370 371
  /** @var \Drupal\Core\Language\LanguageManagerInterface $languageManager */
  $languageManager = \Drupal::languageManager();
  $language_interface = $languageManager->getCurrentLanguage();
  /** @var \Drupal\facets\FacetInterface[] $allFacets */
  $allFacets = \Drupal::entityTypeManager()
    ->getStorage('facets_facet')
    ->loadMultiple();

  /** @var \Drupal\facets\UrlProcessor\UrlProcessorPluginManager $urlProcessorManager */
  $urlProcessorManager = \Drupal::service('plugin.manager.facets.url_processor');
  foreach ($links as &$link) {
372
    if (empty($link['language']) || !($link['language'] instanceof LanguageInterface) || $link['language']->getId() === $language_interface->getId()) {
373 374 375 376
      continue;
    }

    foreach ($allFacets as $facet) {
377 378
      if (!isset($link['query'][$facet->getFacetSourceConfig()->getFilterKey()]) ||
          !is_array($link['query'][$facet->getFacetSourceConfig()->getFilterKey()])) {
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
        continue;
      }

      $configName = 'facets.facet.' . $facet->id();
      $untranslatedAlias = $languageManager->getLanguageConfigOverride($language_interface->getId(), $configName)->get('url_alias');
      $translatedAlias = $languageManager->getLanguageConfigOverride($link['language']->getId(), $configName)->get('url_alias');

      // If we don't have a translated alias, that means we're trying to create
      // a link to the original language.
      if ($translatedAlias === NULL) {
        $translatedAlias = \Drupal::config($configName)->getOriginal('url_alias', FALSE);
      }
      // If we don't have an untranslated alias, we're trying to create a link
      // from the original language.
      if ($untranslatedAlias === NULL) {
        $untranslatedAlias = \Drupal::config($configName)->getOriginal('url_alias', FALSE);
      }

      /** @var \Drupal\facets\UrlProcessor\UrlProcessorInterface $urlProcessor */
      $urlProcessor = $urlProcessorManager
        ->createInstance($facet
          ->getFacetSourceConfig()
          ->getUrlProcessorName(), ['facet' => $facet]
        );

      foreach ($link['query'][$facet->getFacetSourceConfig()->getFilterKey()] as &$filters) {
        $separator = $urlProcessor->getSeparator();
        $filters = preg_replace(
          '/(' . $untranslatedAlias . ")$separator/",
          $translatedAlias . $separator,
          $filters
        );
      }
    }
  }
}
415 416 417 418 419 420 421 422 423 424 425 426 427 428

/**
 * Implements hook_form_FORM_ID_alter().
 */
function facets_form_facets_facet_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $facet_sources = [];
  foreach (\Drupal::service('plugin.manager.facets.facet_source')->getDefinitions() as $facet_source_id => $definition) {
    $facet_sources[$definition['id']] = !empty($definition['label']) ? $definition['label'] : $facet_source_id;
  }

  if (count($facet_sources) == 0) {
    unset($form['actions']);
  }
}
429 430 431 432 433 434 435

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function facets_theme_suggestions_facets_result_item(array $variables) {
  $suggestions = [];
  $facet = $variables['facet'];
436 437 438 439
  if ($facet instanceof FacetInterface) {
    $suggestions[] = 'facets_result_item__' . $facet->getWidget()['type'];
    $suggestions[] = 'facets_result_item__' . $facet->getWidget()['type'] . '__' . $facet->id();
  }
440 441
  return $suggestions;
}