StringFilter.php 10.5 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1
2
3
4
<?php

/**
 * @file
5
 * Contains \Drupal\views\Plugin\views\filter\StringFilter.
merlinofchaos's avatar
merlinofchaos committed
6
7
 */

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

10
use Drupal\Component\Utility\SafeMarkup;
11
use Drupal\Core\Database\Database;
12
use Drupal\Core\Form\FormStateInterface;
13

merlinofchaos's avatar
merlinofchaos committed
14
15
16
17
18
/**
 * Basic textfield filter to handle string filtering commands
 * including equality, like, not like, etc.
 *
 * @ingroup views_filter_handlers
19
 *
20
 * @ViewsFilter("string")
21
 */
22
class StringFilter extends FilterPluginBase {
23

merlinofchaos's avatar
merlinofchaos committed
24
  // exposed filter options
25
  protected $alwaysMultiple = TRUE;
merlinofchaos's avatar
merlinofchaos committed
26

27
28
  protected function defineOptions() {
    $options = parent::defineOptions();
merlinofchaos's avatar
merlinofchaos committed
29

30
    $options['expose']['contains']['required'] = array('default' => FALSE);
merlinofchaos's avatar
merlinofchaos committed
31
32
33
34
35
36
37
38
39
40
41
42

    return $options;
  }

  /**
   * This kind of construct makes it relatively easy for a child class
   * to add or remove functionality by overriding this function and
   * adding/removing items from this array.
   */
  function operators() {
    $operators = array(
      '=' => array(
43
44
        'title' => $this->t('Is equal to'),
        'short' => $this->t('='),
45
        'method' => 'opEqual',
merlinofchaos's avatar
merlinofchaos committed
46
47
48
        'values' => 1,
      ),
      '!=' => array(
49
50
        'title' => $this->t('Is not equal to'),
        'short' => $this->t('!='),
51
        'method' => 'opEqual',
merlinofchaos's avatar
merlinofchaos committed
52
53
54
        'values' => 1,
      ),
      'contains' => array(
55
56
        'title' => $this->t('Contains'),
        'short' => $this->t('contains'),
57
        'method' => 'opContains',
merlinofchaos's avatar
merlinofchaos committed
58
59
60
        'values' => 1,
      ),
      'word' => array(
61
62
        'title' => $this->t('Contains any word'),
        'short' => $this->t('has word'),
63
        'method' => 'opContainsWord',
merlinofchaos's avatar
merlinofchaos committed
64
65
66
        'values' => 1,
      ),
      'allwords' => array(
67
68
        'title' => $this->t('Contains all words'),
        'short' => $this->t('has all'),
69
        'method' => 'opContainsWord',
merlinofchaos's avatar
merlinofchaos committed
70
71
72
        'values' => 1,
      ),
      'starts' => array(
73
74
        'title' => $this->t('Starts with'),
        'short' => $this->t('begins'),
75
        'method' => 'opStartsWith',
merlinofchaos's avatar
merlinofchaos committed
76
77
78
        'values' => 1,
      ),
      'not_starts' => array(
79
80
        'title' => $this->t('Does not start with'),
        'short' => $this->t('not_begins'),
81
        'method' => 'opNotStartsWith',
merlinofchaos's avatar
merlinofchaos committed
82
83
84
        'values' => 1,
      ),
      'ends' => array(
85
86
        'title' => $this->t('Ends with'),
        'short' => $this->t('ends'),
87
        'method' => 'opEndsWith',
merlinofchaos's avatar
merlinofchaos committed
88
89
90
        'values' => 1,
      ),
      'not_ends' => array(
91
92
        'title' => $this->t('Does not end with'),
        'short' => $this->t('not_ends'),
93
        'method' => 'opNotEndsWith',
merlinofchaos's avatar
merlinofchaos committed
94
95
96
        'values' => 1,
      ),
      'not' => array(
97
98
        'title' => $this->t('Does not contain'),
        'short' => $this->t('!has'),
99
        'method' => 'opNotLike',
merlinofchaos's avatar
merlinofchaos committed
100
101
102
        'values' => 1,
      ),
      'shorterthan' => array(
103
104
        'title' => $this->t('Length is shorter than'),
        'short' => $this->t('shorter than'),
105
        'method' => 'opShorterThan',
merlinofchaos's avatar
merlinofchaos committed
106
107
108
        'values' => 1,
      ),
      'longerthan' => array(
109
110
        'title' => $this->t('Length is longer than'),
        'short' => $this->t('longer than'),
111
        'method' => 'opLongerThan',
merlinofchaos's avatar
merlinofchaos committed
112
113
        'values' => 1,
      ),
114
      'regular_expression' => array(
115
116
        'title' => $this->t('Regular expression'),
        'short' => $this->t('regex'),
117
118
119
        'method' => 'opRegex',
        'values' => 1,
      ),
merlinofchaos's avatar
merlinofchaos committed
120
121
122
123
124
    );
    // if the definition allows for the empty operator, add it.
    if (!empty($this->definition['allow empty'])) {
      $operators += array(
        'empty' => array(
125
          'title' => $this->t('Is empty (NULL)'),
126
          'method' => 'opEmpty',
127
          'short' => $this->t('empty'),
merlinofchaos's avatar
merlinofchaos committed
128
129
130
          'values' => 0,
        ),
        'not empty' => array(
131
          'title' => $this->t('Is not empty (NOT NULL)'),
132
          'method' => 'opEmpty',
133
          'short' => $this->t('not empty'),
merlinofchaos's avatar
merlinofchaos committed
134
135
136
137
138
139
140
141
142
143
144
          'values' => 0,
        ),
      );
    }

    return $operators;
  }

  /**
   * Build strings from the operators() for 'select' options
   */
145
  public function operatorOptions($which = 'title') {
merlinofchaos's avatar
merlinofchaos committed
146
147
148
149
150
151
152
153
    $options = array();
    foreach ($this->operators() as $id => $info) {
      $options[$id] = $info[$which];
    }

    return $options;
  }

154
155
  public function adminSummary() {
    if ($this->isAGroup()) {
156
      return $this->t('grouped');
157
    }
merlinofchaos's avatar
merlinofchaos committed
158
    if (!empty($this->options['exposed'])) {
159
      return $this->t('exposed');
merlinofchaos's avatar
merlinofchaos committed
160
161
    }

162
    $options = $this->operatorOptions('short');
merlinofchaos's avatar
merlinofchaos committed
163
    $output = '';
164
    if (!empty($options[$this->operator])) {
165
      $output = SafeMarkup::checkPlain($options[$this->operator]);
merlinofchaos's avatar
merlinofchaos committed
166
    }
167
    if (in_array($this->operator, $this->operatorValues(1))) {
168
      $output .= ' ' . SafeMarkup::checkPlain($this->value);
merlinofchaos's avatar
merlinofchaos committed
169
170
171
172
    }
    return $output;
  }

173
  protected function operatorValues($values = 1) {
merlinofchaos's avatar
merlinofchaos committed
174
175
176
177
178
179
180
181
182
183
184
185
186
    $options = array();
    foreach ($this->operators() as $id => $info) {
      if (isset($info['values']) && $info['values'] == $values) {
        $options[] = $id;
      }
    }

    return $options;
  }

  /**
   * Provide a simple textfield for equality
   */
187
  protected function valueForm(&$form, FormStateInterface $form_state) {
merlinofchaos's avatar
merlinofchaos committed
188
189
190
191
192
193
    // We have to make some choices when creating this as an exposed
    // filter form. For example, if the operator is locked and thus
    // not rendered, we can't render dependencies; instead we only
    // render the form items we need.
    $which = 'all';
    if (!empty($form['operator'])) {
194
      $source = ':input[name="options[operator]"]';
merlinofchaos's avatar
merlinofchaos committed
195
    }
196
    if ($exposed = $form_state->get('exposed')) {
merlinofchaos's avatar
merlinofchaos committed
197
198
199
200
      $identifier = $this->options['expose']['identifier'];

      if (empty($this->options['expose']['use_operator']) || empty($this->options['expose']['operator_id'])) {
        // exposed and locked.
201
        $which = in_array($this->operator, $this->operatorValues(1)) ? 'value' : 'none';
merlinofchaos's avatar
merlinofchaos committed
202
203
      }
      else {
204
        $source = ':input[name="' . $this->options['expose']['operator_id'] . '"]';
merlinofchaos's avatar
merlinofchaos committed
205
206
207
208
209
210
      }
    }

    if ($which == 'all' || $which == 'value') {
      $form['value'] = array(
        '#type' => 'textfield',
211
        '#title' => $this->t('Value'),
merlinofchaos's avatar
merlinofchaos committed
212
213
214
        '#size' => 30,
        '#default_value' => $this->value,
      );
215
      $user_input = $form_state->getUserInput();
216
      if ($exposed && !isset($user_input[$identifier])) {
217
218
        $user_input[$identifier] = $this->value;
        $form_state->setUserInput($user_input);
merlinofchaos's avatar
merlinofchaos committed
219
220
221
      }

      if ($which == 'all') {
222
        // Setup #states for all operators with one value.
223
        foreach ($this->operatorValues(1) as $operator) {
224
225
226
227
          $form['value']['#states']['visible'][] = array(
            $source => array('value' => $operator),
          );
        }
merlinofchaos's avatar
merlinofchaos committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
      }
    }

    if (!isset($form['value'])) {
      // Ensure there is something in the 'value'.
      $form['value'] = array(
        '#type' => 'value',
        '#value' => NULL
      );
    }
  }

  function operator() {
    return $this->operator == '=' ? 'LIKE' : 'NOT LIKE';
  }

  /**
   * Add this filter to the query.
   *
   * Due to the nature of fapi, the value and the operator have an unintended
   * level of indirection. You will find them in $this->operator
   * and $this->value respectively.
   */
251
  public function query() {
252
    $this->ensureMyTable();
253
    $field = "$this->tableAlias.$this->realField";
merlinofchaos's avatar
merlinofchaos committed
254
255
256
257
258
259
260

    $info = $this->operators();
    if (!empty($info[$this->operator]['method'])) {
      $this->{$info[$this->operator]['method']}($field);
    }
  }

261
  public function opEqual($field) {
262
    $this->query->addWhere($this->options['group'], $field, $this->value, $this->operator());
merlinofchaos's avatar
merlinofchaos committed
263
264
  }

265
  protected function opContains($field) {
266
    $this->query->addWhere($this->options['group'], $field, '%' . db_like($this->value) . '%', 'LIKE');
merlinofchaos's avatar
merlinofchaos committed
267
268
  }

269
  protected function opContainsWord($field) {
merlinofchaos's avatar
merlinofchaos committed
270
271
272
273
274
275
276
277
278
    $where = $this->operator == 'word' ? db_or() : db_and();

    // Don't filter on empty strings.
    if (empty($this->value)) {
      return;
    }

    preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $this->value, $matches, PREG_SET_ORDER);
    foreach ($matches as $match) {
279
      $phrase = FALSE;
merlinofchaos's avatar
merlinofchaos committed
280
281
282
      // Strip off phrase quotes
      if ($match[2]{0} == '"') {
        $match[2] = substr($match[2], 1, -1);
283
        $phrase = TRUE;
merlinofchaos's avatar
merlinofchaos committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
      }
      $words = trim($match[2], ',?!();:-');
      $words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
      foreach ($words as $word) {
        $where->condition($field, '%' . db_like(trim($word, " ,!?")) . '%', 'LIKE');
      }
    }

    if (!$where) {
      return;
    }

    // previously this was a call_user_func_array but that's unnecessary
    // as views will unpack an array that is a single arg.
298
    $this->query->addWhere($this->options['group'], $where);
merlinofchaos's avatar
merlinofchaos committed
299
300
  }

301
  protected function opStartsWith($field) {
302
    $this->query->addWhere($this->options['group'], $field, db_like($this->value) . '%', 'LIKE');
merlinofchaos's avatar
merlinofchaos committed
303
304
  }

305
  protected function opNotStartsWith($field) {
306
    $this->query->addWhere($this->options['group'], $field, db_like($this->value) . '%', 'NOT LIKE');
merlinofchaos's avatar
merlinofchaos committed
307
308
  }

309
  protected function opEndsWith($field) {
310
    $this->query->addWhere($this->options['group'], $field, '%' . db_like($this->value), 'LIKE');
merlinofchaos's avatar
merlinofchaos committed
311
312
  }

313
  protected function opNotEndsWith($field) {
314
    $this->query->addWhere($this->options['group'], $field, '%' . db_like($this->value), 'NOT LIKE');
merlinofchaos's avatar
merlinofchaos committed
315
316
  }

317
  protected function opNotLike($field) {
318
    $this->query->addWhere($this->options['group'], $field, '%' . db_like($this->value) . '%', 'NOT LIKE');
merlinofchaos's avatar
merlinofchaos committed
319
320
  }

321
  protected function opShorterThan($field) {
merlinofchaos's avatar
merlinofchaos committed
322
    $placeholder = $this->placeholder();
323
324
325
    // Type cast the argument to an integer because the SQLite database driver
    // has to do some specific alterations to the query base on that data type.
    $this->query->addWhereExpression($this->options['group'], "LENGTH($field) < $placeholder", array($placeholder => (int) $this->value));
merlinofchaos's avatar
merlinofchaos committed
326
327
  }

328
  protected function opLongerThan($field) {
merlinofchaos's avatar
merlinofchaos committed
329
    $placeholder = $this->placeholder();
330
331
332
    // Type cast the argument to an integer because the SQLite database driver
    // has to do some specific alterations to the query base on that data type.
    $this->query->addWhereExpression($this->options['group'], "LENGTH($field) > $placeholder", array($placeholder => (int) $this->value));
merlinofchaos's avatar
merlinofchaos committed
333
334
  }

335
336
337
338
339
340
  /**
   * Filters by a regular expression.
   *
   * @param string $field
   *   The expression pointing to the queries field, for example "foo.bar".
   */
341
  protected function opRegex($field) {
342
    $this->query->addWhere($this->options['group'], $field, $this->value, 'REGEXP');
merlinofchaos's avatar
merlinofchaos committed
343
344
  }

345
  protected function opEmpty($field) {
merlinofchaos's avatar
merlinofchaos committed
346
347
348
349
350
351
352
    if ($this->operator == 'empty') {
      $operator = "IS NULL";
    }
    else {
      $operator = "IS NOT NULL";
    }

353
    $this->query->addWhere($this->options['group'], $field, NULL, $operator);
merlinofchaos's avatar
merlinofchaos committed
354
355
356
  }

}