Search.php 6.14 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\search\Plugin\views\filter\Search.
6 7
 */

8
namespace Drupal\search\Plugin\views\filter;
9

10
use Drupal\Core\Form\FormStateInterface;
11
use Drupal\views\Plugin\views\filter\FilterPluginBase;
12 13 14
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
15 16

/**
17
 * Filter handler for search keywords.
18 19
 *
 * @ingroup views_filter_handlers
20
 *
21
 * @ViewsFilter("search_keywords")
22 23
 */
class Search extends FilterPluginBase {
24

25 26 27 28 29
  /**
   * This filter is always considered multiple-valued.
   *
   * @var bool
   */
30
  protected $alwaysMultiple = TRUE;
31 32

  /**
33 34 35 36 37 38 39 40 41 42 43 44 45
   * A search query to use for parsing search keywords.
    *
    * @var \Drupal\search\ViewsSearchQuery
    */
  protected $searchQuery = NULL;

  /**
   * TRUE if the search query has been parsed.
   */
  protected $parsed = FALSE;

  /**
   * The search type name (value of {search_index}.type in the database).
46
   *
47
   * @var string
48
   */
49
  protected $searchType;
50 51

  /**
52
   * {@inheritdoc}
53
   */
54 55
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
56

57 58 59 60 61 62
    $this->searchType = $this->definition['search_type'];
  }

  /**
   * {@inheritdoc}
   */
63 64
  protected function defineOptions() {
    $options = parent::defineOptions();
65 66 67 68 69 70 71

    $options['operator']['default'] = 'optional';

    return $options;
  }

  /**
72
   * {@inheritdoc}
73
   */
74
  protected function operatorForm(&$form, FormStateInterface $form_state) {
75 76
    $form['operator'] = array(
      '#type' => 'radios',
77
      '#title' => $this->t('On empty input'),
78 79
      '#default_value' => $this->operator,
      '#options' => array(
80 81
        'optional' => $this->t('Show All'),
        'required' => $this->t('Show None'),
82 83 84 85 86
      ),
    );
  }

  /**
87
   * {@inheritdoc}
88
   */
89
  protected function valueForm(&$form, FormStateInterface $form_state) {
90 91 92 93
    $form['value'] = array(
      '#type' => 'textfield',
      '#size' => 15,
      '#default_value' => $this->value,
94
      '#attributes' => array('title' => $this->t('Search keywords')),
95
      '#title' => !$form_state->get('exposed') ? $this->t('Keywords') : '',
96 97 98 99
    );
  }

  /**
100
   * {@inheritdoc}
101
   */
102
  public function validateExposed(&$form, FormStateInterface $form_state) {
103 104 105 106 107
    if (!isset($this->options['expose']['identifier'])) {
      return;
    }

    $key = $this->options['expose']['identifier'];
108 109
    if (!$form_state->isValueEmpty($key)) {
      $this->queryParseSearchExpression($form_state->getValue($key));
110
      if (count($this->searchQuery->words()) == 0) {
111
        $form_state->setErrorByName($key, $this->formatPlural(\Drupal::config('search.settings')->get('index.minimum_word_size'), 'You must include at least one positive keyword with 1 character or more.', 'You must include at least one positive keyword with @count characters or more.'));
112 113 114 115 116
      }
    }
  }

  /**
117
   * Sets up and parses the search query.
118
   *
119 120
   * @param string $input
   *   The search keywords entered by the user.
121
   */
122 123
  protected function queryParseSearchExpression($input) {
    if (!isset($this->searchQuery)) {
124
      $this->parsed = TRUE;
125
      $this->searchQuery = db_select('search_index', 'i', array('target' => 'replica'))->extend('Drupal\search\ViewsSearchQuery');
126 127
      $this->searchQuery->searchExpression($input, $this->searchType);
      $this->searchQuery->publicParseSearchExpression();
128 129 130 131
    }
  }

  /**
132
   * {@inheritdoc}
133
   */
134
  public function query() {
135 136 137
    // Since attachment views don't validate the exposed input, parse the search
    // expression if required.
    if (!$this->parsed) {
138
      $this->queryParseSearchExpression($this->value);
139 140
    }
    $required = FALSE;
141
    if (!isset($this->searchQuery)) {
142 143 144
      $required = TRUE;
    }
    else {
145
      $words = $this->searchQuery->words();
146 147 148 149 150 151
      if (empty($words)) {
        $required = TRUE;
      }
    }
    if ($required) {
      if ($this->operator == 'required') {
152
        $this->query->addWhere($this->options['group'], 'FALSE');
153 154 155
      }
    }
    else {
156
      $search_index = $this->ensureMyTable();
157 158 159

      $search_condition = db_and();

160 161
      // Create a new join to relate the 'search_total' table to our current
      // 'search_index' table.
162 163 164 165 166 167
      $definition = array(
        'table' => 'search_total',
        'field' => 'word',
        'left_table' => $search_index,
        'left_field' => 'word',
      );
168
      $join = Views::pluginManager('join')->createInstance('standard', $definition);
169

170
      $search_total = $this->query->addRelationship('search_total', $join, $search_index);
171

172
      $this->search_score = $this->query->addField('', "SUM($search_index.score * $search_total.count)", 'score', array('aggregate' => TRUE));
173

174 175
      $search_condition->condition("$search_index.type", $this->searchType);
      if (!$this->searchQuery->simple()) {
176
        $search_dataset = $this->query->addTable('search_dataset');
177
        $conditions = $this->searchQuery->conditions();
178 179
        $condition_conditions =& $conditions->conditions();
        foreach ($condition_conditions  as $key => &$condition) {
180
          // Make sure we just look at real conditions.
181 182
          if (is_numeric($key)) {
            // Replace the conditions with the table alias of views.
183
            $this->searchQuery->conditionReplaceString('d.', "$search_dataset.", $condition);
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
          }
        }
        $search_conditions =& $search_condition->conditions();
        $search_conditions = array_merge($search_conditions, $condition_conditions);
      }
      else {
        // Stores each condition, so and/or on the filter level will still work.
        $or = db_or();
        foreach ($words as $word) {
          $or->condition("$search_index.word", $word);
        }

        $search_condition->condition($or);
      }

199
      $this->query->addWhere($this->options['group'], $search_condition);
200
      $this->query->addGroupBy("$search_index.sid");
201
      $matches = $this->searchQuery->matches();
202
      $placeholder = $this->placeholder();
203
      $this->query->addHavingExpression($this->options['group'], "COUNT(*) >= $placeholder", array($placeholder => $matches));
204 205
    }
    // Set to NULL to prevent PDO exception when views object is cached.
206
    $this->searchQuery = NULL;
207
  }
208

209
}