You are here

class FacetsPrettyPathsUrlProcessor in Facets Pretty Paths 8

Pretty paths URL processor.

Plugin annotation


@FacetsUrlProcessor(
  id = "facets_pretty_paths",
  label = @Translation("Pretty paths"),
  description = @Translation("Pretty paths uses slashes as separator, e.g. /brand/drupal/color/blue"),
)

Hierarchy

Expanded class hierarchy of FacetsPrettyPathsUrlProcessor

File

src/Plugin/facets/url_processor/FacetsPrettyPathsUrlProcessor.php, line 25

Namespace

Drupal\facets_pretty_paths\Plugin\facets\url_processor
View source
class FacetsPrettyPathsUrlProcessor extends UrlProcessorPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The current_route_match service.
   *
   * @var \Drupal\Core\Routing\ResettableStackedRouteMatchInterface
   */
  protected $routeMatch;

  /**
   * The service responsible for determining the active filters.
   *
   * @var \Drupal\facets_pretty_paths\PrettyPathsActiveFilters
   */
  protected $activeFiltersService;

  /**
   * Constructs FacetsPrettyPathsUrlProcessor object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   A request object for the current request.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\Core\Routing\RouteMatchInterface $routeMatch
   *   The route match service.
   * @param \Drupal\facets_pretty_paths\PrettyPathsActiveFilters $activeFilters
   *   The active filters service.
   *
   * @throws \Drupal\facets\Exception\InvalidProcessorException
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Request $request, EntityTypeManagerInterface $entity_type_manager, RouteMatchInterface $routeMatch, PrettyPathsActiveFilters $activeFilters) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $request, $entity_type_manager);
    $this->routeMatch = $routeMatch;
    $this->activeFiltersService = $activeFilters;
    $this
      ->initializeActiveFilters();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('request_stack')
      ->getMasterRequest(), $container
      ->get('entity_type.manager'), $container
      ->get('current_route_match'), $container
      ->get('facets_pretty_paths.active_filters'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildUrls(FacetInterface $facet, array $results) {

    // No results are found for this facet, so don't try to create urls.
    if (empty($results)) {
      return [];
    }
    $initialized_coders = [];
    $initialized_facets = [];
    $filters = $this
      ->getActiveFilters();
    $coder_plugin_manager = \Drupal::service('plugin.manager.facets_pretty_paths.coder');
    $coder_id = $facet
      ->getThirdPartySetting('facets_pretty_paths', 'coder', 'default_coder');
    $coder = $coder_plugin_manager
      ->createInstance($coder_id, [
      'facet' => $facet,
    ]);

    /** @var \Drupal\facets\Result\ResultInterface $result */
    foreach ($results as &$result) {
      $raw_value = $result
        ->getRawValue();
      $filters_current_result = $filters;

      // If the value is active, remove the filter string from the parameters.
      if ($result
        ->isActive()) {
        if (($key = array_search($raw_value, $filters_current_result[$result
          ->getFacet()
          ->id()])) !== FALSE) {
          unset($filters_current_result[$result
            ->getFacet()
            ->id()][$key]);
        }
        if ($result
          ->getFacet()
          ->getEnableParentWhenChildGetsDisabled() && $result
          ->getFacet()
          ->getUseHierarchy()) {

          // Enable parent id again if exists.
          $parent_ids = $result
            ->getFacet()
            ->getHierarchyInstance()
            ->getParentIds($raw_value);
          if (isset($parent_ids[0]) && $parent_ids[0]) {
            $filters_current_result[$result
              ->getFacet()
              ->id()][] = $coder
              ->encode($parent_ids[0]);
          }
        }
      }
      else {

        // Exclude others results if we are in the show_only_one_result mode.
        if ($result
          ->getFacet()
          ->getShowOnlyOneResult()) {
          $filters_current_result[$result
            ->getFacet()
            ->id()] = [
            0 => $raw_value,
          ];
        }
        else {
          $filters_current_result[$result
            ->getFacet()
            ->id()][] = $raw_value;
        }
        if ($result
          ->getFacet()
          ->getUseHierarchy()) {

          // If hierarchy is active, unset parent trail and every child when
          // building the enable-link to ensure those are not enabled anymore.
          $parent_ids = $result
            ->getFacet()
            ->getHierarchyInstance()
            ->getParentIds($raw_value);
          $child_ids = $result
            ->getFacet()
            ->getHierarchyInstance()
            ->getNestedChildIds($raw_value);
          $parents_and_child_ids = array_merge($parent_ids, $child_ids);
          foreach ($parents_and_child_ids as $id) {
            if (($key = array_search($id, $filters_current_result[$result
              ->getFacet()
              ->id()])) !== FALSE) {
              unset($filters_current_result[$result
                ->getFacet()
                ->id()][$key]);
            }
          }
        }
      }

      // Now we start transforming $filters_current_result array into a string
      // which we append later to the current path.
      $pretty_paths_presort_data = [];
      foreach ($filters_current_result as $facet_id => $active_values) {
        foreach ($active_values as $active_value) {

          // Ensure we only load every facet and coder once.
          if (!isset($initialized_facets[$facet_id])) {
            $facet = Facet::load($facet_id);
            $initialized_facets[$facet_id] = $facet;
            $coder_id = $facet
              ->getThirdPartySetting('facets_pretty_paths', 'coder', 'default_coder');
            $coder = $coder_plugin_manager
              ->createInstance($coder_id, [
              'facet' => $facet,
            ]);
            $initialized_coders[$facet_id] = $coder;
          }
          $encoded_value = $initialized_coders[$facet_id]
            ->encode($active_value);
          $pretty_paths_presort_data[] = [
            'weight' => $initialized_facets[$facet_id]
              ->getWeight(),
            'name' => $initialized_facets[$facet_id]
              ->getName(),
            'pretty_path_alias' => "/" . $initialized_facets[$facet_id]
              ->getUrlAlias() . "/" . $encoded_value,
          ];
        }
      }
      $pretty_paths_presort_data = $this
        ->sortByWeightAndName($pretty_paths_presort_data);
      $pretty_paths_string = implode('', array_column($pretty_paths_presort_data, 'pretty_path_alias'));
      $url = Url::fromUri('internal:' . $facet
        ->getFacetSource()
        ->getPath() . $pretty_paths_string);
      $url
        ->setOption('attributes', [
        'rel' => 'nofollow',
      ]);

      // First get the current list of get parameters.
      $get_params = $this->request->query;

      // When adding/removing a filter the number of pages may have changed,
      // possibly resulting in an invalid page parameter.
      if ($get_params
        ->has('page')) {
        $current_page = $get_params
          ->get('page');
        $get_params
          ->remove('page');
      }
      $url
        ->setOption('query', $get_params
        ->all());
      $result
        ->setUrl($url);

      // Restore page parameter again. See https://www.drupal.org/node/2726455.
      if (isset($current_page)) {
        $get_params
          ->set('page', $current_page);
      }
    }
    return $results;
  }

  /**
   * Sorts an array with weight and name values.
   *
   * It sorts first by weight, then by the alias of the facet item value.
   *
   * @param array $pretty_paths
   *   The values to sort.
   *
   * @return array
   *   The sorted values.
   */
  public function sortByWeightAndName(array $pretty_paths) {
    array_multisort(array_column($pretty_paths, 'weight'), SORT_ASC, array_column($pretty_paths, 'name'), SORT_ASC, array_column($pretty_paths, 'pretty_path_alias'), SORT_ASC, $pretty_paths);
    return $pretty_paths;
  }

  /**
   * Initializes the active filters from the url.
   *
   * Get all the filters that are active by checking the request url and store
   * them in activeFilters which is an array where key is the facet id and value
   * is an array of raw values.
   */
  protected function initializeActiveFilters() {
    $facet_source_id = $this->configuration['facet']
      ->getFacetSourceId();
    $this->activeFilters = $this->activeFiltersService
      ->getActiveFilters($facet_source_id);
  }

}

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
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
FacetsPrettyPathsUrlProcessor::$activeFiltersService protected property The service responsible for determining the active filters.
FacetsPrettyPathsUrlProcessor::$routeMatch protected property The current_route_match service.
FacetsPrettyPathsUrlProcessor::buildUrls public function Adds urls to the results. Overrides UrlProcessorInterface::buildUrls
FacetsPrettyPathsUrlProcessor::create public static function Creates an instance of the plugin. Overrides UrlProcessorPluginBase::create
FacetsPrettyPathsUrlProcessor::initializeActiveFilters protected function Initializes the active filters from the url.
FacetsPrettyPathsUrlProcessor::sortByWeightAndName public function Sorts an array with weight and name values.
FacetsPrettyPathsUrlProcessor::__construct public function Constructs FacetsPrettyPathsUrlProcessor object. Overrides UrlProcessorPluginBase::__construct
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.
ProcessorInterface::STAGE_BUILD constant Processing stage: build.
ProcessorInterface::STAGE_POST_QUERY constant Processing stage: post_query.
ProcessorInterface::STAGE_PRE_QUERY constant Processing stage: pre_query.
ProcessorInterface::STAGE_SORT constant Processing stage: sort.
ProcessorPluginBase::buildConfigurationForm public function Adds a configuration form for this processor. Overrides ProcessorInterface::buildConfigurationForm 10
ProcessorPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
ProcessorPluginBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 8
ProcessorPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ProcessorPluginBase::getDefaultWeight public function Returns the default weight for a specific processing stage. Overrides ProcessorInterface::getDefaultWeight
ProcessorPluginBase::getDescription public function Retrieves the processor description. Overrides ProcessorInterface::getDescription
ProcessorPluginBase::getQueryType public function Picks the preferred query type for this widget. Overrides ProcessorInterface::getQueryType 4
ProcessorPluginBase::isHidden public function Determines whether this processor should be hidden from the user. Overrides ProcessorInterface::isHidden
ProcessorPluginBase::isLocked public function Determines whether this processor should always be enabled. Overrides ProcessorInterface::isLocked
ProcessorPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ProcessorPluginBase::submitConfigurationForm public function
ProcessorPluginBase::supportsFacet public function Checks if the facet is supported by this widget. Overrides ProcessorInterface::supportsFacet 6
ProcessorPluginBase::supportsStage public function Checks whether this processor implements a particular stage. Overrides ProcessorInterface::supportsStage
ProcessorPluginBase::validateConfigurationForm public function Validates a configuration form for this processor. Overrides ProcessorInterface::validateConfigurationForm 2
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.
UrlProcessorPluginBase::$activeFilters protected property An array of active filters.
UrlProcessorPluginBase::$entityTypeManager protected property The entity type manager.
UrlProcessorPluginBase::$filterKey protected property The query string variable.
UrlProcessorPluginBase::$request protected property The clone of the current request object.
UrlProcessorPluginBase::$separator protected property The url separator variable. 1
UrlProcessorPluginBase::getActiveFilters public function Returns the active filters. Overrides UrlProcessorInterface::getActiveFilters
UrlProcessorPluginBase::getFilterKey public function Returns the filter key. Overrides UrlProcessorInterface::getFilterKey
UrlProcessorPluginBase::getSeparator public function Returns the url separator. Overrides UrlProcessorInterface::getSeparator
UrlProcessorPluginBase::setActiveFilters public function Set active filters. Overrides UrlProcessorInterface::setActiveFilters
UrlProcessorPluginBase::setActiveItems public function Sets active items. Overrides UrlProcessorInterface::setActiveItems