You are here

abstract class WidgetPluginBase in Facets 8

A base class for widgets that implements most of the boilerplate.

Hierarchy

Expanded class hierarchy of WidgetPluginBase

7 files declare their use of WidgetPluginBase
ArrayWidget.php in src/Plugin/facets/widget/ArrayWidget.php
CustomWidget.php in tests/facets_custom_widget/src/Plugin/facets/widget/CustomWidget.php
DropdownWidget.php in src/Plugin/facets/widget/DropdownWidget.php
LinksWidget.php in src/Plugin/facets/widget/LinksWidget.php
SliderWidget.php in modules/facets_range_widget/src/Plugin/facets/widget/SliderWidget.php

... See full list

File

src/Widget/WidgetPluginBase.php, line 18

Namespace

Drupal\facets\Widget
View source
abstract class WidgetPluginBase extends PluginBase implements WidgetPluginInterface {

  /**
   * Show the amount of results next to the result.
   *
   * @var bool
   */
  protected $showNumbers;

  /**
   * The facet the widget is being built for.
   *
   * @var \Drupal\facets\FacetInterface
   */
  protected $facet;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this
      ->setConfiguration($configuration);
  }

  /**
   * {@inheritdoc}
   */
  public function build(FacetInterface $facet) {
    $this->facet = $facet;
    $items = array_map(function (Result $result) use ($facet) {
      if (empty($result
        ->getUrl())) {
        return $this
          ->buildResultItem($result);
      }
      else {

        // When the facet is being build in an AJAX request, and the facetsource
        // is a block, we need to update the url to use the current request url.
        if ($result
          ->getUrl()
          ->isRouted() && $result
          ->getUrl()
          ->getRouteName() === 'facets.block.ajax') {
          $request = \Drupal::request();
          $url_object = \Drupal::service('path.validator')
            ->getUrlIfValid($request
            ->getPathInfo());
          if ($url_object) {
            $url = $result
              ->getUrl();
            $options = $url
              ->getOptions();
            $route_params = $url_object
              ->getRouteParameters();
            $route_name = $url_object
              ->getRouteName();
            $result
              ->setUrl(new Url($route_name, $route_params, $options));
          }
        }
        return $this
          ->buildListItems($facet, $result);
      }
    }, $facet
      ->getResults());
    $widget = $facet
      ->getWidget();
    return [
      '#theme' => $this
        ->getFacetItemListThemeHook($facet),
      '#facet' => $facet,
      '#items' => $items,
      '#attributes' => [
        'data-drupal-facet-id' => $facet
          ->id(),
        'data-drupal-facet-alias' => $facet
          ->getUrlAlias(),
        'class' => [
          $facet
            ->getActiveItems() ? 'facet-active' : 'facet-inactive',
        ],
      ],
      '#context' => !empty($widget['type']) ? [
        'list_style' => $widget['type'],
      ] : [],
      '#cache' => [
        'contexts' => [
          'url.path',
          'url.query_args',
        ],
      ],
    ];
  }

  /**
   * Provides a full array of possible theme functions to try for a given hook.
   *
   * This allows the following template suggestions:
   *  - facets-item-list--WIDGET_TYPE--FACET_ID
   *  - facets-item-list--WIDGET_TYPE
   *  - facets-item-list.
   *
   * @param \Drupal\facets\FacetInterface $facet
   *   The facet whose output is being generated.
   *
   * @return string
   *   A theme hook name with suggestions, suitable for the #theme property.
   */
  protected function getFacetItemListThemeHook(FacetInterface $facet) {
    $type = $facet
      ->getWidget()['type'] ?? 'std';
    return 'facets_item_list__' . $type . '__' . $facet
      ->id();
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'show_numbers' => FALSE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
    $this->configuration = NestedArray::mergeDeep($this
      ->defaultConfiguration(), $configuration);
  }

  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    return $this->configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function getQueryType() {
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state, FacetInterface $facet) {
    $form['show_numbers'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show the amount of results'),
      '#default_value' => $this
        ->getConfiguration()['show_numbers'],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    return [];
  }

  /**
   * Builds a renderable array of result items.
   *
   * @param \Drupal\facets\FacetInterface $facet
   *   The facet we need to build.
   * @param \Drupal\facets\Result\ResultInterface $result
   *   A result item.
   *
   * @return array
   *   A renderable array of the result.
   */
  protected function buildListItems(FacetInterface $facet, ResultInterface $result) {
    $classes = [
      'facet-item',
    ];
    $items = $this
      ->prepareLink($result);
    $children = $result
      ->getChildren();

    // Check if we need to expand this result.
    if ($children && ($this->facet
      ->getExpandHierarchy() || $result
      ->isActive() || $result
      ->hasActiveChildren())) {
      $child_items = [];
      $classes[] = 'facet-item--expanded';
      foreach ($children as $child) {
        $child_items[] = $this
          ->buildListItems($facet, $child);
      }
      $items['children'] = [
        '#theme' => $this
          ->getFacetItemListThemeHook($facet),
        '#items' => $child_items,
      ];
      if ($result
        ->hasActiveChildren()) {
        $classes[] = 'facet-item--active-trail';
      }
    }
    else {
      if ($children) {
        $classes[] = 'facet-item--collapsed';
      }
    }
    if ($result
      ->isActive()) {
      $items['#attributes']['class'][] = 'is-active';
    }
    $items['#wrapper_attributes'] = [
      'class' => $classes,
    ];
    $items['#attributes']['data-drupal-facet-item-id'] = Html::getClass($this->facet
      ->getUrlAlias() . '-' . strtr($result
      ->getRawValue(), ' \'\\"', '---'));
    $items['#attributes']['data-drupal-facet-item-value'] = $result
      ->getRawValue();
    $items['#attributes']['data-drupal-facet-item-count'] = $result
      ->getCount();
    return $items;
  }

  /**
   * Returns the text or link for an item.
   *
   * @param \Drupal\facets\Result\ResultInterface $result
   *   A result item.
   *
   * @return array
   *   The item as a render array.
   */
  protected function prepareLink(ResultInterface $result) {
    $item = $this
      ->buildResultItem($result);
    if (!is_null($result
      ->getUrl())) {
      $item = (new Link($item, $result
        ->getUrl()))
        ->toRenderable();
    }
    return $item;
  }

  /**
   * Builds a facet result item.
   *
   * @param \Drupal\facets\Result\ResultInterface $result
   *   The result item.
   *
   * @return array
   *   The facet result item as a render array.
   */
  protected function buildResultItem(ResultInterface $result) {
    $count = $result
      ->getCount();
    return [
      '#theme' => 'facets_result_item',
      '#is_active' => $result
        ->isActive(),
      '#value' => $result
        ->getDisplayValue(),
      '#show_count' => $this
        ->getConfiguration()['show_numbers'] && $count !== NULL,
      '#count' => $count,
      '#facet' => $result
        ->getFacet(),
      '#raw_value' => $result
        ->getRawValue(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function isPropertyRequired($name, $type) {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function supportsFacet(FacetInterface $facet) {
    return TRUE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
WidgetPluginBase::$facet protected property The facet the widget is being built for.
WidgetPluginBase::$showNumbers protected property Show the amount of results next to the result.
WidgetPluginBase::build public function Builds the facet widget for rendering. Overrides WidgetPluginInterface::build 4
WidgetPluginBase::buildConfigurationForm public function Provides a configuration form for this widget. Overrides WidgetPluginInterface::buildConfigurationForm 3
WidgetPluginBase::buildListItems protected function Builds a renderable array of result items. 1
WidgetPluginBase::buildResultItem protected function Builds a facet result item.
WidgetPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
WidgetPluginBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 3
WidgetPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
WidgetPluginBase::getFacetItemListThemeHook protected function Provides a full array of possible theme functions to try for a given hook.
WidgetPluginBase::getQueryType public function Picks the preferred query type for this widget. Overrides WidgetPluginInterface::getQueryType 3
WidgetPluginBase::isPropertyRequired public function Checks is a specific property is required for this widget. Overrides WidgetPluginInterface::isPropertyRequired 2
WidgetPluginBase::prepareLink protected function Returns the text or link for an item.
WidgetPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
WidgetPluginBase::supportsFacet public function Checks if the facet is supported by this processor. Overrides WidgetPluginInterface::supportsFacet 1
WidgetPluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct