You are here

class GlossaryAZWidgetOrderProcessor in Search API AZ Glossary 8

Same name and namespace in other branches
  1. 8.4 src/Plugin/facets/processor/GlossaryAZWidgetOrderProcessor.php \Drupal\search_api_glossary\Plugin\facets\processor\GlossaryAZWidgetOrderProcessor
  2. 8.2 src/Plugin/facets/processor/GlossaryAZWidgetOrderProcessor.php \Drupal\search_api_glossary\Plugin\facets\processor\GlossaryAZWidgetOrderProcessor
  3. 8.3 src/Plugin/facets/processor/GlossaryAZWidgetOrderProcessor.php \Drupal\search_api_glossary\Plugin\facets\processor\GlossaryAZWidgetOrderProcessor

A processor that orders the results by display value.

Plugin annotation


@FacetsProcessor(
  id = "glossaryaz_widget_order",
  label = @Translation("Sort by Glossary AZ"),
  description = @Translation("Sort order for Glossary AZ items."),
  stages = {
    "sort" = 100
  }
)

Hierarchy

Expanded class hierarchy of GlossaryAZWidgetOrderProcessor

File

src/Plugin/facets/processor/GlossaryAZWidgetOrderProcessor.php, line 23

Namespace

Drupal\search_api_glossary\Plugin\facets\processor
View source
class GlossaryAZWidgetOrderProcessor extends SortProcessorPluginBase implements SortProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function sortResults(Result $a, Result $b) {
    $group_a = $this
      ->getResultGroup($a);
    $group_b = $this
      ->getResultGroup($b);
    if ($group_a == $group_b) {

      // Apply natural sorting within single group.
      return strnatcasecmp($a
        ->getRawValue(), $b
        ->getRawValue());
    }
    else {

      // Get the custom sort order from config.
      $sort_options_by_weight = $this
        ->sortConfigurationWeight($this
        ->getConfiguration()['sort']);
      return $sort_options_by_weight[$group_a] < $sort_options_by_weight[$group_b] ? -1 : 1;
    }
  }

  /**
   * Returns glossary result group.
   */
  private function getResultGroup(Result $result) {

    // Is it a number? or maybe grouped number eg 0-9 (technically a string).
    if ($result
      ->getRawValue() == '0-9' || ctype_digit($result
      ->getRawValue()) || is_int($result
      ->getRawValue())) {
      $group = 'glossaryaz_sort_09';
    }
    elseif ($result
      ->getRawValue() == 'All') {
      $group = 'glossaryaz_sort_all';
    }
    elseif (ctype_alpha($result
      ->getRawValue())) {
      $group = 'glossaryaz_sort_az';
    }
    else {
      $group = 'glossaryaz_sort_other';
    }
    return $group;
  }

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

    // Get the custom sort order from config.
    $sort_options_by_weight = $this
      ->sortConfigurationWeight($this
      ->getConfiguration()['sort']);

    // Initialise an empty array and populate
    // it with options in the same order as the sort
    // order defined in the config.
    $glossary_results = array();
    foreach ($sort_options_by_weight as $sort_option_by_weight_id => $sort_option_by_weight_weight) {
      $glossary_results[$sort_option_by_weight_id] = array();
    }

    // Since our new array is already in
    // the sort order defined in the config
    // lets step through the results and populate
    // results into respective containers.
    foreach ($results as $result) {

      // Is it a number? or maybe grouped number eg 0-9 (technically a string).
      if ($result
        ->getRawValue() == '0-9' || ctype_digit($result
        ->getRawValue()) || is_int($result
        ->getRawValue())) {
        $glossary_results['glossaryaz_sort_09'][$result
          ->getRawValue()] = $result;
      }
      elseif ($result
        ->getRawValue() == 'All') {
        $glossary_results['glossaryaz_sort_all'][$result
          ->getRawValue()] = $result;
      }
      elseif (ctype_alpha($result
        ->getRawValue())) {
        $glossary_results['glossaryaz_sort_az'][$result
          ->getRawValue()] = $result;
      }
      else {
        $glossary_results['glossaryaz_sort_other'][$result
          ->getRawValue()] = $result;
      }
    }
    ksort($glossary_results['glossaryaz_sort_az']);
    ksort($glossary_results['glossaryaz_sort_09']);
    ksort($glossary_results['glossaryaz_sort_other']);

    // Flatten the array to same structure as $results.
    $glossary_results_sorted = array();
    foreach ($glossary_results as $glossary_result) {
      if ($glossary_result) {
        $glossary_results_sorted = array_merge($glossary_results_sorted, $glossary_result);
      }
    }

    // And its done.
    return $glossary_results_sorted;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state, FacetInterface $facet) {
    $processors = $facet
      ->getProcessors();
    $config = isset($processors[$this
      ->getPluginId()]) ? $processors[$this
      ->getPluginId()] : NULL;

    // Get the weight options.
    $sort_options = !is_null($config) ? $config
      ->getConfiguration()['sort'] : $this
      ->defaultConfiguration();
    $sort_options_by_weight = $this
      ->sortConfigurationWeight($sort_options);

    // Build the form.
    $build['sort'] = array(
      '#tree' => TRUE,
      '#type' => 'table',
      '#attributes' => array(
        'id' => 'glossaryaz-sort-widget',
      ),
      '#header' => array(
        $this
          ->t('Sort By'),
        $this
          ->t('Weight'),
      ),
      '#tabledrag' => array(
        array(
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'glossaryaz-sort-weight',
        ),
      ),
    );
    foreach ($sort_options_by_weight as $sort_option_key => $sort_option_weight) {
      $build['sort'][$sort_option_key]['#attributes']['class'][] = 'draggable';
      $build['sort'][$sort_option_key]['#attributes']['class'][] = 'glossaryaz-sort-weight--' . $sort_option_key;
      $build['sort'][$sort_option_key]['#weight'] = $sort_option_weight;
      $build['sort'][$sort_option_key]['sort_by']['#plain_text'] = $this
        ->defaultConfiguration()[$sort_option_key]['name'];
      $build['sort'][$sort_option_key]['weight'] = array(
        '#type' => 'weight',
        '#delta' => count($this
          ->defaultConfiguration()),
        '#default_value' => $sort_option_weight,
        '#attributes' => array(
          'class' => array(
            'glossaryaz-sort-weight',
          ),
        ),
      );
    }
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $sort_options_deafult = array(
      'glossaryaz_sort_az' => array(
        'weight' => 1,
        'name' => $this
          ->t('Alpha (A-Z)'),
      ),
      'glossaryaz_sort_09' => array(
        'weight' => 2,
        'name' => $this
          ->t('Numeric (0-9)'),
      ),
      'glossaryaz_sort_other' => array(
        'weight' => 3,
        'name' => $this
          ->t('Other (#)'),
      ),
      'glossaryaz_sort_all' => array(
        'weight' => -1,
        'name' => $this
          ->t('All'),
      ),
    );
    return $sort_options_deafult;
  }

  /**
   * {@inheritdoc}
   */
  public function sortConfigurationWeight($sort_options) {
    foreach ($sort_options as $sort_option_id => $sort_option) {
      $sort_options_by_weight[$sort_option_id] = $sort_option['weight'];
    }

    // Sort by weight options.
    asort($sort_options_by_weight);
    return $sort_options_by_weight;
  }

}

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.
GlossaryAZWidgetOrderProcessor::build public function
GlossaryAZWidgetOrderProcessor::buildConfigurationForm public function Adds a configuration form for this processor. Overrides SortProcessorPluginBase::buildConfigurationForm
GlossaryAZWidgetOrderProcessor::defaultConfiguration public function Gets default configuration for this plugin. Overrides SortProcessorPluginBase::defaultConfiguration
GlossaryAZWidgetOrderProcessor::getResultGroup private function Returns glossary result group.
GlossaryAZWidgetOrderProcessor::sortConfigurationWeight public function
GlossaryAZWidgetOrderProcessor::sortResults public function Orders results and return the new order of results. Overrides SortProcessorInterface::sortResults
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.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
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::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
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.