9bcd5ba699c988559922fd022451f3a3faa39d36
[yaffs-website] / web / core / modules / views / src / Plugin / views / argument / ArgumentPluginBase.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\argument;
4
5 use Drupal\Component\Plugin\DependentPluginInterface;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Component\Utility\NestedArray;
8 use Drupal\Core\Cache\Cache;
9 use Drupal\Core\Cache\CacheableDependencyInterface;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Core\Render\Element;
12 use Drupal\views\Plugin\views\display\DisplayPluginBase;
13 use Drupal\views\ViewExecutable;
14 use Drupal\views\Plugin\views\HandlerBase;
15 use Drupal\views\Views;
16
17 /**
18  * @defgroup views_argument_handlers Views argument handlers
19  * @{
20  * Handler plugins for Views contextual filters.
21  *
22  * Handler plugins help build the view query object. Views argument handlers
23  * are for contextual filtering.
24  *
25  * Views argument handlers extend
26  * \Drupal\views\Plugin\views\argument\ArgumentPluginBase. They must be
27  * annotated with \Drupal\views\Annotation\ViewsArgument annotation, and they
28  * must be in namespace directory Plugin\views\argument.
29  *
30  * @ingroup views_plugins
31  * @see plugin_api
32  */
33
34 /**
35  * Base class for argument (contextual filter) handler plugins.
36  *
37  * The basic argument works for very simple arguments such as nid and uid
38  *
39  * Definition terms for this handler:
40  * - name field: The field to use for the name to use in the summary, which is
41  *               the displayed output. For example, for the node: nid argument,
42  *               the argument itself is the nid, but node.title is displayed.
43  * - name table: The table to use for the name, should it not be in the same
44  *               table as the argument.
45  * - empty field name: For arguments that can have no value, such as taxonomy
46  *                     which can have "no term", this is the string which
47  *                     will be displayed for this lack of value. Be sure to use
48  *                     $this->t().
49  * - validate type: A little used string to allow an argument to restrict
50  *                  which validator is available to just one. Use the
51  *                  validator ID. This probably should not be used at all,
52  *                  and may disappear or change.
53  * - numeric: If set to TRUE this field is numeric and will use %d instead of
54  *            %s in queries.
55  */
56 abstract class ArgumentPluginBase extends HandlerBase implements CacheableDependencyInterface {
57
58   public $validator = NULL;
59   public $argument = NULL;
60   public $value = NULL;
61
62   /**
63    * The table to use for the name, should it not be in the same table as the argument.
64    * @var string
65    */
66   public $name_table;
67
68   /**
69    * The field to use for the name to use in the summary, which is
70    * the displayed output. For example, for the node: nid argument,
71    * the argument itself is the nid, but node.title is displayed.
72    * @var string
73    */
74   public $name_field;
75
76   /**
77    * Overrides Drupal\views\Plugin\views\HandlerBase:init().
78    */
79   public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
80     parent::init($view, $display, $options);
81
82     if (!empty($this->definition['name field'])) {
83       $this->name_field = $this->definition['name field'];
84     }
85     if (!empty($this->definition['name table'])) {
86       $this->name_table = $this->definition['name table'];
87     }
88   }
89
90   public function isException($arg = NULL) {
91     if (!isset($arg)) {
92       $arg = isset($this->argument) ? $this->argument : NULL;
93     }
94     return !empty($this->options['exception']['value']) && $this->options['exception']['value'] === $arg;
95   }
96
97   public function exceptionTitle() {
98     // If title overriding is off for the exception, return the normal title.
99     if (empty($this->options['exception']['title_enable'])) {
100       return $this->getTitle();
101     }
102     return $this->options['exception']['title'];
103   }
104
105   /**
106    * Determine if the argument needs a style plugin.
107    *
108    * @return bool
109    */
110   public function needsStylePlugin() {
111     $info = $this->defaultActions($this->options['default_action']);
112     $validate_info = $this->defaultActions($this->options['validate']['fail']);
113     return !empty($info['style plugin']) || !empty($validate_info['style plugin']);
114   }
115
116   protected function defineOptions() {
117     $options = parent::defineOptions();
118
119     $options['default_action'] = ['default' => 'ignore'];
120     $options['exception'] = [
121       'contains' => [
122         'value' => ['default' => 'all'],
123         'title_enable' => ['default' => FALSE],
124         'title' => ['default' => 'All'],
125       ],
126     ];
127     $options['title_enable'] = ['default' => FALSE];
128     $options['title'] = ['default' => ''];
129     $options['default_argument_type'] = ['default' => 'fixed'];
130     $options['default_argument_options'] = ['default' => []];
131     $options['default_argument_skip_url'] = ['default' => FALSE];
132     $options['summary_options'] = ['default' => []];
133     $options['summary'] = [
134       'contains' => [
135         'sort_order' => ['default' => 'asc'],
136         'number_of_records' => ['default' => 0],
137         'format' => ['default' => 'default_summary'],
138       ],
139     ];
140     $options['specify_validation'] = ['default' => FALSE];
141     $options['validate'] = [
142       'contains' => [
143         'type' => ['default' => 'none'],
144         'fail' => ['default' => 'not found'],
145       ],
146     ];
147     $options['validate_options'] = ['default' => []];
148
149     return $options;
150   }
151
152   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
153     parent::buildOptionsForm($form, $form_state);
154
155     $argument_text = $this->view->display_handler->getArgumentText();
156
157     $form['#pre_render'][] = [get_class($this), 'preRenderMoveArgumentOptions'];
158
159     $form['description'] = [
160       '#markup' => $argument_text['description'],
161       '#theme_wrappers' => ['container'],
162       '#attributes' => ['class' => ['description']],
163     ];
164
165     $form['no_argument'] = [
166       '#type' => 'details',
167       '#title' => $argument_text['filter value not present'],
168       '#open' => TRUE,
169     ];
170     // Everything in the details is floated, so the last element needs to
171     // clear those floats.
172     $form['no_argument']['clearfix'] = [
173       '#weight' => 1000,
174       '#markup' => '<div class="clearfix"></div>',
175     ];
176     $form['default_action'] = [
177       '#title' => $this->t('Default actions'),
178       '#title_display' => 'invisible',
179       '#type' => 'radios',
180       '#process' => [[$this, 'processContainerRadios']],
181       '#default_value' => $this->options['default_action'],
182       '#fieldset' => 'no_argument',
183     ];
184
185     $form['exception'] = [
186       '#type' => 'details',
187       '#title' => $this->t('Exceptions'),
188       '#fieldset' => 'no_argument',
189     ];
190     $form['exception']['value'] = [
191       '#type' => 'textfield',
192       '#title' => $this->t('Exception value'),
193       '#size' => 20,
194       '#default_value' => $this->options['exception']['value'],
195       '#description' => $this->t('If this value is received, the filter will be ignored; i.e, "all values"'),
196     ];
197     $form['exception']['title_enable'] = [
198       '#type' => 'checkbox',
199       '#title' => $this->t('Override title'),
200       '#default_value' => $this->options['exception']['title_enable'],
201     ];
202     $form['exception']['title'] = [
203       '#type' => 'textfield',
204       '#title' => $this->t('Override title'),
205       '#title_display' => 'invisible',
206       '#size' => 20,
207       '#default_value' => $this->options['exception']['title'],
208       '#description' => $this->t('Override the view and other argument titles. You may use Twig syntax in this field as well as the "arguments" and "raw_arguments" arrays.'),
209       '#states' => [
210         'visible' => [
211           ':input[name="options[exception][title_enable]"]' => ['checked' => TRUE],
212         ],
213       ],
214     ];
215
216     $options = [];
217     $defaults = $this->defaultActions();
218     $validate_options = [];
219     foreach ($defaults as $id => $info) {
220       $options[$id] = $info['title'];
221       if (empty($info['default only'])) {
222         $validate_options[$id] = $info['title'];
223       }
224       if (!empty($info['form method'])) {
225         $this->{$info['form method']}($form, $form_state);
226       }
227     }
228     $form['default_action']['#options'] = $options;
229
230     $form['argument_present'] = [
231       '#type' => 'details',
232       '#title' => $argument_text['filter value present'],
233       '#open' => TRUE,
234     ];
235     $form['title_enable'] = [
236       '#type' => 'checkbox',
237       '#title' => $this->t('Override title'),
238       '#default_value' => $this->options['title_enable'],
239       '#fieldset' => 'argument_present',
240     ];
241     $form['title'] = [
242       '#type' => 'textfield',
243       '#title' => $this->t('Provide title'),
244       '#title_display' => 'invisible',
245       '#default_value' => $this->options['title'],
246       '#description' => $this->t('Override the view and other argument titles. You may use Twig syntax in this field.'),
247       '#states' => [
248         'visible' => [
249           ':input[name="options[title_enable]"]' => ['checked' => TRUE],
250         ],
251       ],
252       '#fieldset' => 'argument_present',
253     ];
254
255     $output = $this->getTokenHelp();
256     $form['token_help'] = [
257       '#type' => 'details',
258       '#title' => $this->t('Replacement patterns'),
259       '#value' => $output,
260       '#states' => [
261         'visible' => [
262           [
263             ':input[name="options[title_enable]"]' => ['checked' => TRUE],
264           ],
265           [
266             ':input[name="options[exception][title_enable]"]' => ['checked' => TRUE],
267           ],
268         ],
269       ],
270     ];
271
272     $form['specify_validation'] = [
273       '#type' => 'checkbox',
274       '#title' => $this->t('Specify validation criteria'),
275       '#default_value' => $this->options['specify_validation'],
276       '#fieldset' => 'argument_present',
277     ];
278
279     $form['validate'] = [
280       '#type' => 'container',
281       '#fieldset' => 'argument_present',
282     ];
283     // Validator options include derivatives with :. These are sanitized for js
284     // and reverted on submission.
285     $form['validate']['type'] = [
286       '#type' => 'select',
287       '#title' => $this->t('Validator'),
288       '#default_value' => static::encodeValidatorId($this->options['validate']['type']),
289       '#states' => [
290         'visible' => [
291           ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
292         ],
293       ],
294     ];
295
296     $plugins = Views::pluginManager('argument_validator')->getDefinitions();
297     foreach ($plugins as $id => $info) {
298       if (!empty($info['no_ui'])) {
299         continue;
300       }
301
302       $valid = TRUE;
303       if (!empty($info['type'])) {
304         $valid = FALSE;
305         if (empty($this->definition['validate type'])) {
306           continue;
307         }
308         foreach ((array) $info['type'] as $type) {
309           if ($type == $this->definition['validate type']) {
310             $valid = TRUE;
311             break;
312           }
313         }
314       }
315
316       // If we decide this validator is ok, add it to the list.
317       if ($valid) {
318         $plugin = $this->getPlugin('argument_validator', $id);
319         if ($plugin) {
320           if ($plugin->access() || $this->options['validate']['type'] == $id) {
321             // Sanitize ID for js.
322             $sanitized_id = static::encodeValidatorId($id);
323             $form['validate']['options'][$sanitized_id] = [
324               '#prefix' => '<div id="edit-options-validate-options-' . $sanitized_id . '-wrapper">',
325               '#suffix' => '</div>',
326               '#type' => 'item',
327               // Even if the plugin has no options add the key to the form_state.
328               // trick it into checking input to make #process run.
329               '#input' => TRUE,
330               '#states' => [
331                 'visible' => [
332                   ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
333                   ':input[name="options[validate][type]"]' => ['value' => $sanitized_id],
334                 ],
335               ],
336               '#id' => 'edit-options-validate-options-' . $sanitized_id,
337               '#default_value' => [],
338             ];
339             $plugin->buildOptionsForm($form['validate']['options'][$sanitized_id], $form_state);
340             $validate_types[$sanitized_id] = $info['title'];
341           }
342         }
343       }
344     }
345
346     asort($validate_types);
347     $form['validate']['type']['#options'] = $validate_types;
348
349     $form['validate']['fail'] = [
350       '#type' => 'select',
351       '#title' => $this->t('Action to take if filter value does not validate'),
352       '#default_value' => $this->options['validate']['fail'],
353       '#options' => $validate_options,
354       '#states' => [
355         'visible' => [
356           ':input[name="options[specify_validation]"]' => ['checked' => TRUE],
357         ],
358       ],
359       '#fieldset' => 'argument_present',
360     ];
361   }
362
363   /**
364    * Provide token help information for the argument.
365    *
366    * @return array
367    *   A render array.
368    */
369   protected function getTokenHelp() {
370     $output = [];
371
372     foreach ($this->view->display_handler->getHandlers('argument') as $arg => $handler) {
373       /** @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase $handler */
374       $options[(string) t('Arguments')]["{{ arguments.$arg }}"] = $this->t('@argument title', ['@argument' => $handler->adminLabel()]);
375       $options[(string) t('Arguments')]["{{ raw_arguments.$arg }}"] = $this->t('@argument input', ['@argument' => $handler->adminLabel()]);
376     }
377
378     // We have some options, so make a list.
379     if (!empty($options)) {
380       $output[] = [
381         '#markup' => '<p>' . $this->t("The following replacement tokens are available for this argument.") . '</p>',
382       ];
383       foreach (array_keys($options) as $type) {
384         if (!empty($options[$type])) {
385           $items = [];
386           foreach ($options[$type] as $key => $value) {
387             $items[] = $key . ' == ' . $value;
388           }
389           $item_list = [
390             '#theme' => 'item_list',
391             '#items' => $items,
392           ];
393           $output[] = $item_list;
394         }
395       }
396     }
397
398     return $output;
399   }
400
401
402   public function validateOptionsForm(&$form, FormStateInterface $form_state) {
403     $option_values = &$form_state->getValue('options');
404     if (empty($option_values)) {
405       return;
406     }
407
408     // Let the plugins do validation.
409     $default_id = $option_values['default_argument_type'];
410     $plugin = $this->getPlugin('argument_default', $default_id);
411     if ($plugin) {
412       $plugin->validateOptionsForm($form['argument_default'][$default_id], $form_state, $option_values['argument_default'][$default_id]);
413     }
414
415     // summary plugin
416     $summary_id = $option_values['summary']['format'];
417     $plugin = $this->getPlugin('style', $summary_id);
418     if ($plugin) {
419       $plugin->validateOptionsForm($form['summary']['options'][$summary_id], $form_state, $option_values['summary']['options'][$summary_id]);
420     }
421
422     $sanitized_id = $option_values['validate']['type'];
423     // Correct ID for js sanitized version.
424     $validate_id = static::decodeValidatorId($sanitized_id);
425     $plugin = $this->getPlugin('argument_validator', $validate_id);
426     if ($plugin) {
427       $plugin->validateOptionsForm($form['validate']['options'][$default_id], $form_state, $option_values['validate']['options'][$sanitized_id]);
428     }
429
430   }
431
432   public function submitOptionsForm(&$form, FormStateInterface $form_state) {
433     $option_values = &$form_state->getValue('options');
434     if (empty($option_values)) {
435       return;
436     }
437
438     // Let the plugins make submit modifications if necessary.
439     $default_id = $option_values['default_argument_type'];
440     $plugin = $this->getPlugin('argument_default', $default_id);
441     if ($plugin) {
442       $options = &$option_values['argument_default'][$default_id];
443       $plugin->submitOptionsForm($form['argument_default'][$default_id], $form_state, $options);
444       // Copy the now submitted options to their final resting place so they get saved.
445       $option_values['default_argument_options'] = $options;
446     }
447
448     // summary plugin
449     $summary_id = $option_values['summary']['format'];
450     $plugin = $this->getPlugin('style', $summary_id);
451     if ($plugin) {
452       $options = &$option_values['summary']['options'][$summary_id];
453       $plugin->submitOptionsForm($form['summary']['options'][$summary_id], $form_state, $options);
454       // Copy the now submitted options to their final resting place so they get saved.
455       $option_values['summary_options'] = $options;
456     }
457
458     // If the 'Specify validation criteria' checkbox is not checked, reset the
459     // validation options.
460     if (empty($option_values['specify_validation'])) {
461       $option_values['validate']['type'] = 'none';
462       // We need to keep the empty array of options for the 'None' plugin as
463       // it will be needed later.
464       $option_values['validate']['options'] = ['none' => []];
465       $option_values['validate']['fail'] = 'not found';
466     }
467
468     $sanitized_id = $option_values['validate']['type'];
469     // Correct ID for js sanitized version.
470     $option_values['validate']['type'] = $validate_id = static::decodeValidatorId($sanitized_id);
471     $plugin = $this->getPlugin('argument_validator', $validate_id);
472     if ($plugin) {
473       $options = &$option_values['validate']['options'][$sanitized_id];
474       $plugin->submitOptionsForm($form['validate']['options'][$sanitized_id], $form_state, $options);
475       // Copy the now submitted options to their final resting place so they get saved.
476       $option_values['validate_options'] = $options;
477     }
478
479     // Clear out the content of title if it's not enabled.
480     if (empty($option_values['title_enable'])) {
481       $option_values['title'] = '';
482     }
483   }
484
485   /**
486    * Provide a list of default behaviors for this argument if the argument
487    * is not present.
488    *
489    * Override this method to provide additional (or fewer) default behaviors.
490    */
491   protected function defaultActions($which = NULL) {
492     $defaults = [
493       'ignore' => [
494         'title' => $this->t('Display all results for the specified field'),
495         'method' => 'defaultIgnore',
496       ],
497       'default' => [
498         'title' => $this->t('Provide default value'),
499         'method' => 'defaultDefault',
500         'form method' => 'defaultArgumentForm',
501         'has default argument' => TRUE,
502         // This can only be used for missing argument, not validation failure.
503         'default only' => TRUE,
504       ],
505       'not found' => [
506         'title' => $this->t('Hide view'),
507         'method' => 'defaultNotFound',
508         // This is a hard fail condition.
509         'hard fail' => TRUE,
510       ],
511       'summary' => [
512         'title' => $this->t('Display a summary'),
513         'method' => 'defaultSummary',
514         'form method' => 'defaultSummaryForm',
515         'style plugin' => TRUE,
516       ],
517       'empty' => [
518         'title' => $this->t('Display contents of "No results found"'),
519         'method' => 'defaultEmpty',
520       ],
521       'access denied' => [
522         'title' => $this->t('Display "Access Denied"'),
523         'method' => 'defaultAccessDenied',
524       ],
525     ];
526
527     if ($this->view->display_handler->hasPath()) {
528       $defaults['not found']['title'] = $this->t('Show "Page not found"');
529     }
530
531     if ($which) {
532       if (!empty($defaults[$which])) {
533         return $defaults[$which];
534       }
535     }
536     else {
537       return $defaults;
538     }
539   }
540
541   /**
542    * Provide a form for selecting the default argument when the
543    * default action is set to provide default argument.
544    */
545   public function defaultArgumentForm(&$form, FormStateInterface $form_state) {
546     $plugins = Views::pluginManager('argument_default')->getDefinitions();
547     $options = [];
548
549     $form['default_argument_skip_url'] = [
550       '#type' => 'checkbox',
551       '#title' => $this->t('Skip default argument for view URL'),
552       '#default_value' => $this->options['default_argument_skip_url'],
553       '#description' => $this->t('Select whether to include this default argument when constructing the URL for this view. Skipping default arguments is useful e.g. in the case of feeds.')
554     ];
555
556     $form['default_argument_type'] = [
557       '#prefix' => '<div id="edit-options-default-argument-type-wrapper">',
558       '#suffix' => '</div>',
559       '#type' => 'select',
560       '#id' => 'edit-options-default-argument-type',
561       '#title' => $this->t('Type'),
562       '#default_value' => $this->options['default_argument_type'],
563       '#states' => [
564         'visible' => [
565           ':input[name="options[default_action]"]' => ['value' => 'default'],
566         ],
567       ],
568       // Views custom key, moves this element to the appropriate container
569       // under the radio button.
570       '#argument_option' => 'default',
571     ];
572
573     foreach ($plugins as $id => $info) {
574       if (!empty($info['no_ui'])) {
575         continue;
576       }
577       $plugin = $this->getPlugin('argument_default', $id);
578       if ($plugin) {
579         if ($plugin->access() || $this->options['default_argument_type'] == $id) {
580           $form['argument_default']['#argument_option'] = 'default';
581           $form['argument_default'][$id] = [
582             '#prefix' => '<div id="edit-options-argument-default-options-' . $id . '-wrapper">',
583             '#suffix' => '</div>',
584             '#id' => 'edit-options-argument-default-options-' . $id,
585             '#type' => 'item',
586             // Even if the plugin has no options add the key to the form_state.
587             '#input' => TRUE,
588             '#states' => [
589               'visible' => [
590                 ':input[name="options[default_action]"]' => ['value' => 'default'],
591                 ':input[name="options[default_argument_type]"]' => ['value' => $id],
592               ],
593             ],
594             '#default_value' => [],
595           ];
596           $options[$id] = $info['title'];
597           $plugin->buildOptionsForm($form['argument_default'][$id], $form_state);
598         }
599       }
600     }
601
602     asort($options);
603     $form['default_argument_type']['#options'] = $options;
604   }
605
606   /**
607    * Provide a form for selecting further summary options when the
608    * default action is set to display one.
609    */
610   public function defaultSummaryForm(&$form, FormStateInterface $form_state) {
611     $style_plugins = Views::pluginManager('style')->getDefinitions();
612     $summary_plugins = [];
613     $format_options = [];
614     foreach ($style_plugins as $key => $plugin) {
615       if (isset($plugin['display_types']) && in_array('summary', $plugin['display_types'])) {
616         $summary_plugins[$key] = $plugin;
617         $format_options[$key] = $plugin['title'];
618       }
619     }
620
621     $form['summary'] = [
622       // Views custom key, moves this element to the appropriate container
623       // under the radio button.
624       '#argument_option' => 'summary',
625     ];
626     $form['summary']['sort_order'] = [
627       '#type' => 'radios',
628       '#title' => $this->t('Sort order'),
629       '#options' => ['asc' => $this->t('Ascending'), 'desc' => $this->t('Descending')],
630       '#default_value' => $this->options['summary']['sort_order'],
631       '#states' => [
632         'visible' => [
633           ':input[name="options[default_action]"]' => ['value' => 'summary'],
634         ],
635       ],
636     ];
637     $form['summary']['number_of_records'] = [
638       '#type' => 'radios',
639       '#title' => $this->t('Sort by'),
640       '#default_value' => $this->options['summary']['number_of_records'],
641       '#options' => [
642         0 => $this->getSortName(),
643         1 => $this->t('Number of records')
644       ],
645       '#states' => [
646         'visible' => [
647           ':input[name="options[default_action]"]' => ['value' => 'summary'],
648         ],
649       ],
650     ];
651
652     $form['summary']['format'] = [
653       '#type' => 'radios',
654       '#title' => $this->t('Format'),
655       '#options' => $format_options,
656       '#default_value' => $this->options['summary']['format'],
657       '#states' => [
658         'visible' => [
659           ':input[name="options[default_action]"]' => ['value' => 'summary'],
660         ],
661       ],
662     ];
663
664     foreach ($summary_plugins as $id => $info) {
665       $plugin = $this->getPlugin('style', $id);
666       if (!$plugin->usesOptions()) {
667         continue;
668       }
669       if ($plugin) {
670         $form['summary']['options'][$id] = [
671           '#prefix' => '<div id="edit-options-summary-options-' . $id . '-wrapper">',
672           '#suffix' => '</div>',
673           '#id' => 'edit-options-summary-options-' . $id,
674           '#type' => 'item',
675           // Trick it into checking input to make #process run.
676           '#input' => TRUE,
677           '#states' => [
678             'visible' => [
679               ':input[name="options[default_action]"]' => ['value' => 'summary'],
680               ':input[name="options[summary][format]"]' => ['value' => $id],
681             ],
682           ],
683           '#default_value' => [],
684         ];
685         $options[$id] = $info['title'];
686         $plugin->buildOptionsForm($form['summary']['options'][$id], $form_state);
687       }
688     }
689   }
690
691   /**
692    * Handle the default action, which means our argument wasn't present.
693    *
694    * Override this method only with extreme care.
695    *
696    * @return
697    *   A boolean value; if TRUE, continue building this view. If FALSE,
698    *   building the view will be aborted here.
699    */
700   public function defaultAction($info = NULL) {
701     if (!isset($info)) {
702       $info = $this->defaultActions($this->options['default_action']);
703     }
704
705     if (!$info) {
706       return FALSE;
707     }
708
709     if (!empty($info['method args'])) {
710       return call_user_func_array([&$this, $info['method']], $info['method args']);
711     }
712     else {
713       return $this->{$info['method']}();
714     }
715   }
716
717   /**
718    * How to act if validation fails.
719    */
720   public function validateFail() {
721     $info = $this->defaultActions($this->options['validate']['fail']);
722     return $this->defaultAction($info);
723   }
724   /**
725    * Default action: ignore.
726    *
727    * If an argument was expected and was not given, in this case, simply
728    * ignore the argument entirely.
729    */
730   public function defaultIgnore() {
731     return TRUE;
732   }
733
734   /**
735    * Default action: not found.
736    *
737    * If an argument was expected and was not given, in this case, report
738    * the view as 'not found' or hide it.
739    */
740   protected function defaultNotFound() {
741     // Set a failure condition and let the display manager handle it.
742     $this->view->build_info['fail'] = TRUE;
743     return FALSE;
744   }
745
746   /**
747    * Default action: access denied.
748    *
749    * If an argument was expected and was not given, in this case, report
750    * the view as 'access denied'.
751    */
752   public function defaultAccessDenied() {
753     $this->view->build_info['denied'] = TRUE;
754     return FALSE;
755   }
756
757   /**
758    * Default action: empty
759    *
760    * If an argument was expected and was not given, in this case, display
761    * the view's empty text
762    */
763   public function defaultEmpty() {
764     // We return with no query; this will force the empty text.
765     $this->view->built = TRUE;
766     $this->view->executed = TRUE;
767     $this->view->result = [];
768     return FALSE;
769   }
770
771   /**
772    * This just returns true. The view argument builder will know where
773    * to find the argument from.
774    */
775   protected function defaultDefault() {
776     return TRUE;
777   }
778
779   /**
780    * Determine if the argument is set to provide a default argument.
781    */
782   public function hasDefaultArgument() {
783     $info = $this->defaultActions($this->options['default_action']);
784     return !empty($info['has default argument']);
785   }
786
787   /**
788    * Get a default argument, if available.
789    */
790   public function getDefaultArgument() {
791     $plugin = $this->getPlugin('argument_default');
792     if ($plugin) {
793       return $plugin->getArgument();
794     }
795   }
796
797   /**
798    * Process the summary arguments for display.
799    *
800    * For example, the validation plugin may want to alter an argument for use in
801    * the URL.
802    */
803   public function processSummaryArguments(&$args) {
804     if ($this->options['validate']['type'] != 'none') {
805       if (isset($this->validator) || $this->validator = $this->getPlugin('argument_validator')) {
806         $this->validator->processSummaryArguments($args);
807       }
808     }
809   }
810
811   /**
812    * Default action: summary.
813    *
814    * If an argument was expected and was not given, in this case, display
815    * a summary query.
816    */
817   protected function defaultSummary() {
818     $this->view->build_info['summary'] = TRUE;
819     $this->view->build_info['summary_level'] = $this->options['id'];
820
821     // Change the display style to the summary style for this
822     // argument.
823     $this->view->style_plugin = Views::pluginManager("style")->createInstance($this->options['summary']['format']);
824     $this->view->style_plugin->init($this->view, $this->displayHandler, $this->options['summary_options']);
825
826     // Clear out the normal primary field and whatever else may have
827     // been added and let the summary do the work.
828     $this->query->clearFields();
829     $this->summaryQuery();
830
831     $by = $this->options['summary']['number_of_records'] ? 'num_records' : NULL;
832     $this->summarySort($this->options['summary']['sort_order'], $by);
833
834     // Summaries have their own sorting and fields, so tell the View not
835     // to build these.
836     $this->view->build_sort = FALSE;
837     return TRUE;
838   }
839
840   /**
841    * Build the info for the summary query.
842    *
843    * This must:
844    * - addGroupBy: group on this field in order to create summaries.
845    * - addField: add a 'num_nodes' field for the count. Usually it will
846    *   be a count on $view->base_field
847    * - setCountField: Reset the count field so we get the right paging.
848    *
849    * @return
850    *   The alias used to get the number of records (count) for this entry.
851    */
852   protected function summaryQuery() {
853     $this->ensureMyTable();
854     // Add the field.
855     $this->base_alias = $this->query->addField($this->tableAlias, $this->realField);
856
857     $this->summaryNameField();
858     return $this->summaryBasics();
859   }
860
861   /**
862    * Add the name field, which is the field displayed in summary queries.
863    * This is often used when the argument is numeric.
864    */
865   protected function summaryNameField() {
866     // Add the 'name' field. For example, if this is a uid argument, the
867     // name field would be 'name' (i.e, the username).
868
869     if (isset($this->name_table)) {
870       // if the alias is different then we're probably added, not ensured,
871       // so look up the join and add it instead.
872       if ($this->tableAlias != $this->name_table) {
873         $j = HandlerBase::getTableJoin($this->name_table, $this->table);
874         if ($j) {
875           $join = clone $j;
876           $join->leftTable = $this->tableAlias;
877           $this->name_table_alias = $this->query->addTable($this->name_table, $this->relationship, $join);
878         }
879       }
880       else {
881         $this->name_table_alias = $this->query->ensureTable($this->name_table, $this->relationship);
882       }
883     }
884     else {
885       $this->name_table_alias = $this->tableAlias;
886     }
887
888     if (isset($this->name_field)) {
889       $this->name_alias = $this->query->addField($this->name_table_alias, $this->name_field);
890     }
891     else {
892       $this->name_alias = $this->base_alias;
893     }
894   }
895
896   /**
897    * Some basic summary behavior that doesn't need to be repeated as much as
898    * code that goes into summaryQuery()
899    */
900   public function summaryBasics($count_field = TRUE) {
901     // Add the number of nodes counter
902     $distinct = ($this->view->display_handler->getOption('distinct') && empty($this->query->no_distinct));
903
904     $count_alias = $this->query->addField($this->view->storage->get('base_table'), $this->view->storage->get('base_field'), 'num_records', ['count' => TRUE, 'distinct' => $distinct]);
905     $this->query->addGroupBy($this->name_alias);
906
907     if ($count_field) {
908       $this->query->setCountField($this->tableAlias, $this->realField);
909     }
910
911     $this->count_alias = $count_alias;
912   }
913
914   /**
915    * Sorts the summary based upon the user's selection. The base variant of
916    * this is usually adequate.
917    *
918    * @param $order
919    *   The order selected in the UI.
920    */
921   public function summarySort($order, $by = NULL) {
922     $this->query->addOrderBy(NULL, NULL, $order, (!empty($by) ? $by : $this->name_alias));
923   }
924
925   /**
926    * Provide the argument to use to link from the summary to the next level;
927    * this will be called once per row of a summary, and used as part of
928    * $view->getUrl().
929    *
930    * @param $data
931    *   The query results for the row.
932    */
933   public function summaryArgument($data) {
934     return $data->{$this->base_alias};
935   }
936
937   /**
938    * Provides the name to use for the summary. By default this is just
939    * the name field.
940    *
941    * @param $data
942    *   The query results for the row.
943    */
944   public function summaryName($data) {
945     $value = $data->{$this->name_alias};
946     if (empty($value) && !empty($this->definition['empty field name'])) {
947       $value = $this->definition['empty field name'];
948     }
949     return $value;
950   }
951
952   /**
953    * Set up the query for this argument.
954    *
955    * The argument sent may be found at $this->argument.
956    */
957   public function query($group_by = FALSE) {
958     $this->ensureMyTable();
959     $this->query->addWhere(0, "$this->tableAlias.$this->realField", $this->argument);
960   }
961
962   /**
963    * Get the title this argument will assign the view, given the argument.
964    *
965    * This usually needs to be overridden to provide a proper title.
966    */
967   public function title() {
968     return $this->argument;
969   }
970
971   /**
972    * Called by the view object to get the title. This may be set by a
973    * validator so we don't necessarily call through to title().
974    */
975   public function getTitle() {
976     if (isset($this->validated_title)) {
977       return $this->validated_title;
978     }
979     else {
980       return $this->title();
981     }
982   }
983
984   /**
985    * Validate that this argument works. By default, all arguments are valid.
986    */
987   public function validateArgument($arg) {
988     // By using % in URLs, arguments could be validated twice; this eases
989     // that pain.
990     if (isset($this->argument_validated)) {
991       return $this->argument_validated;
992     }
993
994     if ($this->isException($arg)) {
995       return $this->argument_validated = TRUE;
996     }
997
998     $plugin = $this->getPlugin('argument_validator');
999     return $this->argument_validated = $plugin->validateArgument($arg);
1000   }
1001
1002   /**
1003    * Called by the menu system to validate an argument.
1004    *
1005    * This checks to see if this is a 'soft fail', which means that if the
1006    * argument fails to validate, but there is an action to take anyway,
1007    * then validation cannot actually fail.
1008    */
1009   public function validateMenuArgument($arg) {
1010     $validate_info = $this->defaultActions($this->options['validate']['fail']);
1011     if (empty($validate_info['hard fail'])) {
1012       return TRUE;
1013     }
1014
1015     $rc = $this->validateArgument($arg);
1016
1017     // If the validator has changed the validate fail condition to a
1018     // soft fail, deal with that:
1019     $validate_info = $this->defaultActions($this->options['validate']['fail']);
1020     if (empty($validate_info['hard fail'])) {
1021       return TRUE;
1022     }
1023
1024     return $rc;
1025   }
1026
1027   /**
1028    * Set the input for this argument
1029    *
1030    * @return TRUE if it successfully validates; FALSE if it does not.
1031    */
1032   public function setArgument($arg) {
1033     $this->argument = $arg;
1034     return $this->validateArgument($arg);
1035   }
1036
1037   /**
1038    * Get the value of this argument.
1039    */
1040   public function getValue() {
1041     // If we already processed this argument, we're done.
1042     if (isset($this->argument)) {
1043       return $this->argument;
1044     }
1045
1046     // Otherwise, we have to pretend to process ourselves to find the value.
1047     $value = NULL;
1048     // Find the position of this argument within the view.
1049     $position = 0;
1050     foreach ($this->view->argument as $id => $argument) {
1051       if ($id == $this->options['id']) {
1052         break;
1053       }
1054       $position++;
1055     }
1056
1057     $arg = isset($this->view->args[$position]) ? $this->view->args[$position] : NULL;
1058     $this->position = $position;
1059
1060     // Clone ourselves so that we don't break things when we're really
1061     // processing the arguments.
1062     $argument = clone $this;
1063     if (!isset($arg) && $argument->hasDefaultArgument()) {
1064       $arg = $argument->getDefaultArgument();
1065
1066       // remember that this argument was computed, not passed on the URL.
1067       $this->is_default = TRUE;
1068     }
1069     // Set the argument, which will also validate that the argument can be set.
1070     if ($argument->setArgument($arg)) {
1071       $value = $argument->argument;
1072     }
1073     unset($argument);
1074     return $value;
1075   }
1076
1077   /**
1078    * Get the display or row plugin, if it exists.
1079    */
1080   public function getPlugin($type = 'argument_default', $name = NULL) {
1081     $options = [];
1082     switch ($type) {
1083       case 'argument_default':
1084         if (!isset($this->options['default_argument_type'])) {
1085           return;
1086         }
1087         $plugin_name = $this->options['default_argument_type'];
1088         $options_name = 'default_argument_options';
1089         break;
1090       case 'argument_validator':
1091         if (!isset($this->options['validate']['type'])) {
1092           return;
1093         }
1094         $plugin_name = $this->options['validate']['type'];
1095         $options_name = 'validate_options';
1096         break;
1097       case 'style':
1098         if (!isset($this->options['summary']['format'])) {
1099           return;
1100         }
1101         $plugin_name = $this->options['summary']['format'];
1102         $options_name = 'summary_options';
1103     }
1104
1105     if (!$name) {
1106       $name = $plugin_name;
1107     }
1108
1109     // we only fetch the options if we're fetching the plugin actually
1110     // in use.
1111     if ($name == $plugin_name) {
1112       $options = isset($this->options[$options_name]) ? $this->options[$options_name] : [];
1113     }
1114
1115     $plugin = Views::pluginManager($type)->createInstance($name);
1116     if ($plugin) {
1117       $plugin->init($this->view, $this->displayHandler, $options);
1118
1119       if ($type !== 'style') {
1120         // It's an argument_default/argument_validate plugin, so set the argument.
1121         $plugin->setArgument($this);
1122       }
1123       return $plugin;
1124     }
1125   }
1126
1127   /**
1128    * Return a description of how the argument would normally be sorted.
1129    *
1130    * Subclasses should override this to specify what the default sort order of
1131    * their argument is (e.g. alphabetical, numeric, date).
1132    */
1133   public function getSortName() {
1134     return $this->t('Default sort', [], ['context' => 'Sort order']);
1135   }
1136
1137   /**
1138    * Custom form radios process function.
1139    *
1140    * Roll out a single radios element to a list of radios, using the options
1141    * array as index. While doing that, create a container element underneath
1142    * each option, which contains the settings related to that option.
1143    *
1144    * @see \Drupal\Core\Render\Element\Radios::processRadios()
1145    */
1146   public static function processContainerRadios($element) {
1147     if (count($element['#options']) > 0) {
1148       foreach ($element['#options'] as $key => $choice) {
1149         $element += [$key => []];
1150         // Generate the parents as the autogenerator does, so we will have a
1151         // unique id for each radio button.
1152         $parents_for_id = array_merge($element['#parents'], [$key]);
1153
1154         $element[$key] += [
1155           '#type' => 'radio',
1156           '#title' => $choice,
1157           // The key is sanitized in drupal_attributes() during output from the
1158           // theme function.
1159           '#return_value' => $key,
1160           '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : NULL,
1161           '#attributes' => $element['#attributes'],
1162           '#parents' => $element['#parents'],
1163           '#id' => Html::getUniqueId('edit-' . implode('-', $parents_for_id)),
1164           '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
1165         ];
1166         $element[$key . '_options'] = [
1167           '#type' => 'container',
1168           '#attributes' => ['class' => ['views-admin-dependent']],
1169         ];
1170       }
1171     }
1172     return $element;
1173   }
1174
1175   /**
1176    * Moves argument options into their place.
1177    *
1178    * When configuring the default argument behavior, almost each of the radio
1179    * buttons has its own fieldset shown below it when the radio button is
1180    * clicked. That fieldset is created through a custom form process callback.
1181    * Each element that has #argument_option defined and pointing to a default
1182    * behavior gets moved to the appropriate fieldset.
1183    * So if #argument_option is specified as 'default', the element is moved
1184    * to the 'default_options' fieldset.
1185    */
1186   public static function preRenderMoveArgumentOptions($form) {
1187     foreach (Element::children($form) as $key) {
1188       $element = $form[$key];
1189       if (!empty($element['#argument_option'])) {
1190         $container_name = $element['#argument_option'] . '_options';
1191         if (isset($form['no_argument']['default_action'][$container_name])) {
1192           $form['no_argument']['default_action'][$container_name][$key] = $element;
1193         }
1194         // Remove the original element this duplicates.
1195         unset($form[$key]);
1196       }
1197     }
1198
1199     return $form;
1200   }
1201
1202   /**
1203    * Sanitize validator options including derivatives with : for js.
1204    *
1205    * Reason and alternative: https://www.drupal.org/node/2035345.
1206    *
1207    * @param string $id
1208    *   The identifier to be sanitized.
1209    *
1210    * @return string
1211    *   The sanitized identifier.
1212    *
1213    * @see decodeValidatorId()
1214    */
1215   public static function encodeValidatorId($id) {
1216     return str_replace(':', '---', $id);
1217   }
1218
1219   /**
1220    * Revert sanitized validator options.
1221    *
1222    * @param string $id
1223    *   The sanitized identifier to be reverted.
1224    *
1225    * @return string
1226    *   The original identifier.
1227    */
1228   public static function decodeValidatorId($id) {
1229     return str_replace('---', ':', $id);
1230   }
1231
1232   /**
1233    * Splits an argument into value and operator properties on this instance.
1234    *
1235    * @param bool $force_int
1236    *   Enforce that values should be numeric.
1237    */
1238   protected function unpackArgumentValue($force_int = FALSE) {
1239     $break = static::breakString($this->argument, $force_int);
1240     $this->value = $break->value;
1241     $this->operator = $break->operator;
1242   }
1243
1244   /**
1245    * {@inheritdoc}
1246    */
1247   public function getCacheMaxAge() {
1248     $max_age = Cache::PERMANENT;
1249
1250     // Asks all subplugins (argument defaults, argument validator and styles).
1251     if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1252       $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1253     }
1254
1255     if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1256       $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1257     }
1258
1259     // Summaries use style plugins.
1260     if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1261       $max_age = Cache::mergeMaxAges($max_age, $plugin->getCacheMaxAge());
1262     }
1263
1264     return $max_age;
1265   }
1266
1267   /**
1268    * {@inheritdoc}
1269    */
1270   public function getCacheContexts() {
1271     $contexts = [];
1272     // By definition arguments depends on the URL.
1273     // @todo Once contexts are properly injected into block views we could pull
1274     //   the information from there.
1275     $contexts[] = 'url';
1276
1277     // Asks all subplugins (argument defaults, argument validator and styles).
1278     if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1279       $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1280     }
1281
1282     if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1283       $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1284     }
1285
1286     if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1287       $contexts = Cache::mergeContexts($contexts, $plugin->getCacheContexts());
1288     }
1289
1290     return $contexts;
1291   }
1292
1293   /**
1294    * {@inheritdoc}
1295    */
1296   public function getCacheTags() {
1297     $tags = [];
1298
1299     // Asks all subplugins (argument defaults, argument validator and styles).
1300     if (($plugin = $this->getPlugin('argument_default')) && $plugin instanceof CacheableDependencyInterface) {
1301       $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1302     }
1303
1304     if (($plugin = $this->getPlugin('argument_validator')) && $plugin instanceof CacheableDependencyInterface) {
1305       $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1306     }
1307
1308     if (($plugin = $this->getPlugin('style')) && $plugin instanceof CacheableDependencyInterface) {
1309       $tags = Cache::mergeTags($tags, $plugin->getCacheTags());
1310     }
1311
1312     return $tags;
1313   }
1314
1315   /**
1316    * {@inheritdoc}
1317    */
1318   public function calculateDependencies() {
1319     $dependencies = [];
1320     if (($argument_default = $this->getPlugin('argument_default')) && $argument_default instanceof DependentPluginInterface) {
1321       $dependencies = NestedArray::mergeDeep($dependencies, $argument_default->calculateDependencies());
1322     }
1323     if (($argument_validator = $this->getPlugin('argument_validator')) && $argument_validator instanceof DependentPluginInterface) {
1324       $dependencies = NestedArray::mergeDeep($dependencies, $argument_validator->calculateDependencies());
1325     }
1326     if (($style = $this->getPlugin('style')) && $style instanceof DependentPluginInterface) {
1327       $dependencies = NestedArray::mergeDeep($dependencies, $style->calculateDependencies());
1328     }
1329
1330     return $dependencies;
1331   }
1332
1333   /**
1334    * Returns a context definition for this argument.
1335    *
1336    * @return \Drupal\Core\Plugin\Context\ContextDefinitionInterface|null
1337    *   A context definition that represents the argument or NULL if that is
1338    *   not possible.
1339    */
1340   public function getContextDefinition() {
1341     return $this->getPlugin('argument_validator')->getContextDefinition();
1342   }
1343
1344 }
1345
1346 /**
1347  * @}
1348  */