3 namespace Drupal\views\Plugin\views\filter;
5 use Drupal\Core\Form\FormStateInterface;
8 * Basic textfield filter to handle string filtering commands
9 * including equality, like, not like, etc.
11 * @ingroup views_filter_handlers
13 * @ViewsFilter("string")
15 class StringFilter extends FilterPluginBase {
18 * All words separated by spaces or sentences encapsulated by double quotes.
20 const WORDS_PATTERN = '/ (-?)("[^"]+"|[^" ]+)/i';
22 // exposed filter options
23 protected $alwaysMultiple = TRUE;
25 protected function defineOptions() {
26 $options = parent::defineOptions();
28 $options['expose']['contains']['required'] = ['default' => FALSE];
34 * This kind of construct makes it relatively easy for a child class
35 * to add or remove functionality by overriding this function and
36 * adding/removing items from this array.
38 public function operators() {
41 'title' => $this->t('Is equal to'),
42 'short' => $this->t('='),
43 'method' => 'opEqual',
47 'title' => $this->t('Is not equal to'),
48 'short' => $this->t('!='),
49 'method' => 'opEqual',
53 'title' => $this->t('Contains'),
54 'short' => $this->t('contains'),
55 'method' => 'opContains',
59 'title' => $this->t('Contains any word'),
60 'short' => $this->t('has word'),
61 'method' => 'opContainsWord',
65 'title' => $this->t('Contains all words'),
66 'short' => $this->t('has all'),
67 'method' => 'opContainsWord',
71 'title' => $this->t('Starts with'),
72 'short' => $this->t('begins'),
73 'method' => 'opStartsWith',
77 'title' => $this->t('Does not start with'),
78 'short' => $this->t('not_begins'),
79 'method' => 'opNotStartsWith',
83 'title' => $this->t('Ends with'),
84 'short' => $this->t('ends'),
85 'method' => 'opEndsWith',
89 'title' => $this->t('Does not end with'),
90 'short' => $this->t('not_ends'),
91 'method' => 'opNotEndsWith',
95 'title' => $this->t('Does not contain'),
96 'short' => $this->t('!has'),
97 'method' => 'opNotLike',
101 'title' => $this->t('Length is shorter than'),
102 'short' => $this->t('shorter than'),
103 'method' => 'opShorterThan',
107 'title' => $this->t('Length is longer than'),
108 'short' => $this->t('longer than'),
109 'method' => 'opLongerThan',
112 'regular_expression' => [
113 'title' => $this->t('Regular expression'),
114 'short' => $this->t('regex'),
115 'method' => 'opRegex',
119 // if the definition allows for the empty operator, add it.
120 if (!empty($this->definition['allow empty'])) {
123 'title' => $this->t('Is empty (NULL)'),
124 'method' => 'opEmpty',
125 'short' => $this->t('empty'),
129 'title' => $this->t('Is not empty (NOT NULL)'),
130 'method' => 'opEmpty',
131 'short' => $this->t('not empty'),
141 * Build strings from the operators() for 'select' options
143 public function operatorOptions($which = 'title') {
145 foreach ($this->operators() as $id => $info) {
146 $options[$id] = $info[$which];
152 public function adminSummary() {
153 if ($this->isAGroup()) {
154 return $this->t('grouped');
156 if (!empty($this->options['exposed'])) {
157 return $this->t('exposed');
160 $options = $this->operatorOptions('short');
162 if (!empty($options[$this->operator])) {
163 $output = $options[$this->operator];
165 if (in_array($this->operator, $this->operatorValues(1))) {
166 $output .= ' ' . $this->value;
171 protected function operatorValues($values = 1) {
173 foreach ($this->operators() as $id => $info) {
174 if (isset($info['values']) && $info['values'] == $values) {
183 * Provide a simple textfield for equality
185 protected function valueForm(&$form, FormStateInterface $form_state) {
186 // We have to make some choices when creating this as an exposed
187 // filter form. For example, if the operator is locked and thus
188 // not rendered, we can't render dependencies; instead we only
189 // render the form items we need.
191 if (!empty($form['operator'])) {
192 $source = ':input[name="options[operator]"]';
194 if ($exposed = $form_state->get('exposed')) {
195 $identifier = $this->options['expose']['identifier'];
197 if (empty($this->options['expose']['use_operator']) || empty($this->options['expose']['operator_id'])) {
198 // exposed and locked.
199 $which = in_array($this->operator, $this->operatorValues(1)) ? 'value' : 'none';
202 $source = ':input[name="' . $this->options['expose']['operator_id'] . '"]';
206 if ($which == 'all' || $which == 'value') {
208 '#type' => 'textfield',
209 '#title' => $this->t('Value'),
211 '#default_value' => $this->value,
213 $user_input = $form_state->getUserInput();
214 if ($exposed && !isset($user_input[$identifier])) {
215 $user_input[$identifier] = $this->value;
216 $form_state->setUserInput($user_input);
219 if ($which == 'all') {
220 // Setup #states for all operators with one value.
221 foreach ($this->operatorValues(1) as $operator) {
222 $form['value']['#states']['visible'][] = [
223 $source => ['value' => $operator],
229 if (!isset($form['value'])) {
230 // Ensure there is something in the 'value'.
238 public function operator() {
239 return $this->operator == '=' ? 'LIKE' : 'NOT LIKE';
243 * Add this filter to the query.
245 * Due to the nature of fapi, the value and the operator have an unintended
246 * level of indirection. You will find them in $this->operator
247 * and $this->value respectively.
249 public function query() {
250 $this->ensureMyTable();
251 $field = "$this->tableAlias.$this->realField";
253 $info = $this->operators();
254 if (!empty($info[$this->operator]['method'])) {
255 $this->{$info[$this->operator]['method']}($field);
259 public function opEqual($field) {
260 $this->query->addWhere($this->options['group'], $field, $this->value, $this->operator());
263 protected function opContains($field) {
264 $this->query->addWhere($this->options['group'], $field, '%' . db_like($this->value) . '%', 'LIKE');
267 protected function opContainsWord($field) {
268 $where = $this->operator == 'word' ? db_or() : db_and();
270 // Don't filter on empty strings.
271 if (empty($this->value)) {
275 preg_match_all(static::WORDS_PATTERN, ' ' . $this->value, $matches, PREG_SET_ORDER);
276 foreach ($matches as $match) {
278 // Strip off phrase quotes
279 if ($match[2]{0} == '"') {
280 $match[2] = substr($match[2], 1, -1);
283 $words = trim($match[2], ',?!();:-');
284 $words = $phrase ? [$words] : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
285 foreach ($words as $word) {
286 $where->condition($field, '%' . db_like(trim($word, " ,!?")) . '%', 'LIKE');
290 if ($where->count() === 0) {
294 // previously this was a call_user_func_array but that's unnecessary
295 // as views will unpack an array that is a single arg.
296 $this->query->addWhere($this->options['group'], $where);
299 protected function opStartsWith($field) {
300 $this->query->addWhere($this->options['group'], $field, db_like($this->value) . '%', 'LIKE');
303 protected function opNotStartsWith($field) {
304 $this->query->addWhere($this->options['group'], $field, db_like($this->value) . '%', 'NOT LIKE');
307 protected function opEndsWith($field) {
308 $this->query->addWhere($this->options['group'], $field, '%' . db_like($this->value), 'LIKE');
311 protected function opNotEndsWith($field) {
312 $this->query->addWhere($this->options['group'], $field, '%' . db_like($this->value), 'NOT LIKE');
315 protected function opNotLike($field) {
316 $this->query->addWhere($this->options['group'], $field, '%' . db_like($this->value) . '%', 'NOT LIKE');
319 protected function opShorterThan($field) {
320 $placeholder = $this->placeholder();
321 // Type cast the argument to an integer because the SQLite database driver
322 // has to do some specific alterations to the query base on that data type.
323 $this->query->addWhereExpression($this->options['group'], "LENGTH($field) < $placeholder", [$placeholder => (int) $this->value]);
326 protected function opLongerThan($field) {
327 $placeholder = $this->placeholder();
328 // Type cast the argument to an integer because the SQLite database driver
329 // has to do some specific alterations to the query base on that data type.
330 $this->query->addWhereExpression($this->options['group'], "LENGTH($field) > $placeholder", [$placeholder => (int) $this->value]);
334 * Filters by a regular expression.
336 * @param string $field
337 * The expression pointing to the queries field, for example "foo.bar".
339 protected function opRegex($field) {
340 $this->query->addWhere($this->options['group'], $field, $this->value, 'REGEXP');
343 protected function opEmpty($field) {
344 if ($this->operator == 'empty') {
345 $operator = "IS NULL";
348 $operator = "IS NOT NULL";
351 $this->query->addWhere($this->options['group'], $field, NULL, $operator);