You are here

public function ArgOrderSort::query in Views Argument Order Sort 8

Same name and namespace in other branches
  1. 2.x src/Plugin/views/sort/ArgOrderSort.php \Drupal\views_arg_order_sort\Plugin\views\sort\ArgOrderSort::query()

Called to add the sort to a query.

Overrides SortPluginBase::query

File

src/Plugin/views/sort/ArgOrderSort.php, line 90

Class

ArgOrderSort
Handle a random sort.

Namespace

Drupal\views_arg_order_sort\Plugin\views\sort

Code

public function query() {

  // Retrieve options.
  $arg_to_use = $this->options['argument_number'];
  $inherit_type = $this->options['inherit_type'];
  $order = $this->options['order'];
  $null_below = $this->options['null_below'];

  // If inherited look at the argument to get table and field.
  if ($inherit_type) {
    $arg_handlers = array_values($this->view->argument);
    $arg_handler = $arg_handlers[$arg_to_use];
    $left_table = $arg_handler->tableAlias;
    $left_field = $arg_handler->realField;
  }
  else {
    [
      $left_table,
      $left_field,
    ] = explode('::', $this->options['field_type']);
  }

  // The arguments passed into the view.
  $args = $this->view->args;
  $items = isset($args[$arg_to_use]) ? preg_split("/(\\+|\\,)/", $args[$arg_to_use]) : [];

  // Get our sort order.
  $invert_order = $order == 'DESC';
  $items = $invert_order ? array_reverse($items) : $items;

  // Defaults.
  $max_o = 0;
  $case_items = [];

  // Attempt to determine the number appended to the query substitutes.
  // Calling the placeholder function increments the placeholder count by 1,
  // so we subtract one to get the number that was used before.
  $placeholder_suffix = str_replace(':' . $left_table . '_' . $left_field, '', $this->query
    ->placeholder($left_table . '_' . $left_field));
  if (!empty($placeholder_suffix) && intval($placeholder_suffix) > 1) {
    $placeholder_suffix = intval($placeholder_suffix) - 1;
  }
  else {

    // No 0 for suffix, so just remove.
    $placeholder_suffix = '';
  }
  $value_query_type = ':' . $left_table . '_' . $left_field . $placeholder_suffix;

  // Generate the case statement from the args.
  if (count($items) == 1) {
    $this->sort_values[0] = 0;
    $case_items[] = "WHEN " . $value_query_type . " THEN 0 ";
  }
  else {
    foreach ($items as $o => $value) {
      $this->sort_values[$value] = $o;
      if ($value) {
        $case_items[] = "WHEN " . $value_query_type . "__{$o} THEN {$o} ";
        $max_o = $max_o > $o ? $max_o : $o;
      }
    }
  }

  // If the case statement items are populated.
  if (!empty($case_items)) {
    $is_desc = $order == 'DESC';
    $null_o = $is_desc == $null_below ? -1 : $max_o + 1;
    $order_by = "CASE {$left_table}.{$left_field} " . implode("", $case_items) . " ELSE {$null_o} END";
    $alias = "arg_order" . rand(0, 10000);
    $this->query
      ->addOrderBy(NULL, $order_by, $order, $alias);
  }
}