Coverage index

src/Plugin/views/area/VisitorsDisplayLink.php

Lines: 4.41%

LineHitsSource
1
<?php
2
3
namespace Drupal\visitors\Plugin\views\area;
4
5
use Drupal\Core\Config\ImmutableConfig;
6
use Drupal\Core\EventSubscriber\AjaxResponseSubscriber;
7
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
8
use Drupal\Core\Form\FormBuilderInterface;
9
use Drupal\Core\Form\FormStateInterface;
10
use Drupal\Core\Url;
11
use Drupal\views\Attribute\ViewsArea;
12
use Drupal\views\Plugin\views\area\DisplayLink;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
15
/**
16
 * Views area display_link handler.
17
 *
18
 * @ingroup views_area_handlers
19
 */
20
#[ViewsArea("visitors_display_link")]
21
class VisitorsDisplayLink extends DisplayLink {
22
23
  /**
24
   * The view settings.
25
   *
26
   * @var \Drupal\Core\Config\ImmutableConfig
27
   */
28
  protected $viewSettings;
29
30
  /**
31
   * Constructs a new VisitorsDisplayLink object.
32
   *
33
   * @param array $configuration
34
   *   The plugin configuration.
35
   * @param string $plugin_id
36
   *   The plugin ID.
37
   * @param mixed $plugin_definition
38
   *   The plugin definition.
39
   * @param \Drupal\Core\Config\ImmutableConfig $view_settings
40
   *   The view settings.
41
   */
42
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ImmutableConfig $view_settings) {
4311
    parent::__construct($configuration, $plugin_id, $plugin_definition);
4411
    $this->viewSettings = $view_settings;
45
  }
46
47
  /**
48
   * {@inheritdoc}
49
   */
50
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
5111
    return new self(
5211
      $configuration,
5311
      $plugin_id,
5411
      $plugin_definition,
5511
      $container->get('config.factory')->get('views.settings')
5611
    );
57
  }
58
59
  /**
60
   * {@inheritdoc}
61
   */
62
  protected function defineOptions() {
6311
    $options = parent::defineOptions();
6411
    $options['display_links'] = ['default' => []];
6511
    $options['render_format'] = ['default' => 'link'];
6611
    return $options;
67
  }
68
69
  /**
70
   * {@inheritdoc}
71
   */
72
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
730
    parent::buildOptionsForm($form, $form_state);
74
750
    $allowed_displays = [];
760
    $displays = $this->view->storage->get('display');
770
    foreach ($displays as $display_id => $display) {
780
      if ($this->isPathBasedDisplay($display_id)) {
790
        unset($displays[$display_id]);
800
        continue;
81
      }
820
      $allowed_displays[$display_id] = $display['display_title'];
83
    }
84
850
    $form['description'] = [
860
      [
870
        '#markup' => $this->t('To make sure the results are the same when switching to the other display, it is recommended to make sure the display:'),
880
      ],
890
      [
900
        '#theme' => 'item_list',
910
        '#items' => [
920
          $this->t('Has a path.'),
930
          $this->t('Has the same filter criteria.'),
940
          $this->t('Has the same sort criteria.'),
950
          $this->t('Has the same contextual filters.'),
960
        ],
970
      ],
980
    ];
99
1000
    if (!$allowed_displays) {
1010
      $form['empty_message'] = [
1020
        '#markup' => '<p><em>' . $this->t('There are no path-based displays available.') . '</em></p>',
1030
      ];
104
    }
105
    else {
106
      // Render format selection.
1070
      $form['render_format'] = [
1080
        '#title' => $this->t('Render format'),
1090
        '#type' => 'select',
1100
        '#options' => [
1110
          'link' => $this->t('Single link (if only one display)'),
1120
          'radio' => $this->t('Radio buttons'),
1130
          'checkboxes' => $this->t('Checkboxes'),
1140
          'list' => $this->t('Unordered list of links'),
1150
        ],
1160
        '#default_value' => (string) ($this->options['render_format'] ?? 'link'),
1170
        '#description' => $this->t('Choose how to render the display links.'),
1180
      ];
119
120
      // Display links configuration.
1210
      $form['display_links'] = [
1220
        '#type' => 'fieldset',
1230
        '#title' => $this->t('Display Links'),
1240
        '#description' => $this->t('Configure multiple display links. Each link can have its own label.'),
1250
        '#tree' => TRUE,
1260
      ];
127
1280
      $display_links = $this->options['display_links'] ?? [];
1290
      if (empty($display_links)) {
130
        // Initialize with one empty link if none exist.
1310
        $display_links = [['display_id' => '', 'label' => '']];
132
      }
133
      else {
134
        // Always add an empty link at the end for adding new ones.
1350
        $display_links[] = ['display_id' => '', 'label' => ''];
136
      }
137
1380
      $total_links = count($display_links);
1390
      foreach ($display_links as $index => $link) {
140
        // Ensure we have a valid array structure.
1410
        if (!is_array($link)) {
142
          continue;
143
        }
144
1450
        $is_empty = empty((string) ($link['display_id'] ?? '')) && empty((string) ($link['label'] ?? ''));
1460
        $is_last = ($index === $total_links - 1);
147
1480
        $form['display_links'][$index] = [
1490
          '#type' => 'fieldset',
1500
          '#title' => $is_empty ? $this->t('Add new link') : $this->t('Link @index', ['@index' => (int) $index + 1]),
1510
          '#collapsible' => TRUE,
1520
          '#collapsed' => $is_empty ? FALSE : ($index > 0),
1530
        ];
154
1550
        $form['display_links'][$index]['display_id'] = [
1560
          '#title' => $this->t('Display'),
1570
          '#type' => 'select',
1580
          '#options' => ['' => $this->t('- Select -')] + $allowed_displays,
1590
          '#default_value' => (string) ($link['display_id'] ?? ''),
1600
          '#required' => !$is_empty,
1610
        ];
162
1630
        $form['display_links'][$index]['label'] = [
1640
          '#title' => $this->t('Label'),
1650
          '#description' => $this->t('The text of the link.'),
1660
          '#type' => 'textfield',
1670
          '#default_value' => (string) ($link['label'] ?? ''),
1680
          '#required' => !$is_empty,
1690
        ];
170
171
        // Only show remove button for non-empty links that are not the last
172
        // one.
1730
        if (!$is_empty && !$is_last) {
1740
          $form['display_links'][$index]['remove'] = [
1750
            '#type' => 'submit',
1760
            '#value' => $this->t('Remove'),
1770
            '#name' => 'remove_link_' . $index,
1780
            '#submit' => [[$this, 'removeDisplayLink']],
1790
          ];
180
        }
181
      }
182
183
    }
184
  }
185
186
  /**
187
   * AJAX callback to remove a display link.
188
   */
189
  public function removeDisplayLink(array &$form, FormStateInterface $form_state) {
1900
    $triggering_element = $form_state->getTriggeringElement();
1910
    $index = (int) str_replace('remove_link_', '', $triggering_element['#name']);
192
1930
    $display_links = $form_state->getValue('display_links', []);
1940
    unset($display_links[$index]);
195
    // Re-index array.
1960
    $display_links = array_values($display_links);
1970
    $form_state->setValue('display_links', $display_links);
1980
    $form_state->setRebuild();
199
  }
200
201
  /**
202
   * {@inheritdoc}
203
   */
204
  public function validate() {
2050
    $errors = [];
206
207
    // Do not add errors for the default display if it is not displayed in the
208
    // UI.
2090
    if ($this->displayHandler->isDefaultDisplay() && !$this->viewSettings->get('ui.show.default_display')) {
2100
      return $errors;
211
    }
212
213
    // Validate new display links configuration.
2140
    $display_links = $this->options['display_links'] ?? [];
2150
    if (!empty($display_links)) {
2160
      foreach ($display_links as $index => $link) {
217
        // Ensure we have valid array structure and convert values to strings.
2180
        if (!is_array($link) || empty($link['display_id']) || empty($link['label'])) {
219
          // Skip empty links.
220
          continue;
221
        }
222
2230
        $linked_display_id = (string) $link['display_id'];
2240
        $link_label = (string) $link['label'];
225
226
        // Check if the linked display hasn't been removed.
2270
        if (!$this->view->displayHandlers->get($linked_display_id)) {
2280
          $errors[] = $this->t('%current_display: Link @index in the %area area points to the %linked_display display which no longer exists.', [
2290
            '%current_display' => $this->displayHandler->display['display_title'],
2300
            '@index' => $index + 1,
2310
            '%area' => $this->areaType,
2320
            '%linked_display' => $linked_display_id,
2330
          ]);
2340
          continue;
235
        }
236
237
        // Check if the linked display is a path-based display.
2380
        if ($this->isPathBasedDisplay($linked_display_id)) {
2390
          $errors[] = $this->t('%current_display: Link @index in the %area area points to the %linked_display display which does not have a path.', [
2400
            '%current_display' => $this->displayHandler->display['display_title'],
2410
            '@index' => $index + 1,
2420
            '%area' => $this->areaType,
2430
            '%linked_display' => $this->view->displayHandlers->get($linked_display_id)->display['display_title'],
2440
          ]);
2450
          continue;
246
        }
247
248
        // Check if options of the linked display are equal to the options of
249
        // the current display. We "only" show a warning here, because even
250
        // though we recommend keeping the display options equal, we do not want
251
        // to enforce this.
2520
        $unequal_options = [
2530
          'filters' => $this->t('Filter criteria'),
2540
          'arguments' => $this->t('Contextual filters'),
2550
        ];
2560
        foreach (array_keys($unequal_options) as $option) {
2570
          if ($this->hasEqualOptions($linked_display_id, $option)) {
2580
            unset($unequal_options[$option]);
259
          }
260
        }
261
2620
        if ($unequal_options) {
2630
          $warning = $this->t('%current_display: Link @index in the %area area points to the %linked_display display which uses different settings than the %current_display display for: %unequal_options. To make sure users see the exact same result when clicking the link, please check that the settings are the same.', [
2640
            '%current_display' => $this->displayHandler->display['display_title'],
2650
            '@index' => $index + 1,
2660
            '%area' => $this->areaType,
2670
            '%linked_display' => $this->view->displayHandlers->get($linked_display_id)->display['display_title'],
2680
            '%unequal_options' => implode(', ', $unequal_options),
2690
          ]);
2700
          $this->messenger()->addWarning($warning);
271
        }
272
      }
273
274
      // If we have display links configured, return any errors found.
2750
      if (!empty($errors)) {
2760
        return $errors;
277
      }
278
    }
279
280
    // If no display links are configured at all, show an error.
2810
    if (empty($display_links)) {
2820
      $errors[] = $this->t('%current_display: The link in the %area area has no configured display.', [
2830
        '%current_display' => $this->displayHandler->display['display_title'],
2840
        '%area' => $this->areaType,
2850
      ]);
286
    }
287
2880
    return $errors;
289
  }
290
291
  /**
292
   * {@inheritdoc}
293
   */
294
  public function render($empty = FALSE) {
2950
    if ($empty && empty($this->options['empty'])) {
2960
      return [];
297
    }
298
299
    // Get display links configuration.
3000
    $display_links = $this->options['display_links'] ?? [];
3010
    $render_format = $this->options['render_format'] ?? 'link';
302
303
    // Filter out empty links.
3040
    $display_links = array_filter($display_links, function ($link) {
3050
      return is_array($link) && !empty($link['display_id']) && !empty($link['label']);
3060
    });
307
3080
    if (empty($display_links)) {
3090
      return [];
310
    }
311
312
    // Filter out path-based displays.
3130
    $valid_links = [];
3140
    foreach ($display_links as $link) {
3150
      if (!$this->isPathBasedDisplay($link['display_id'])) {
3160
        $valid_links[] = $link;
317
      }
318
    }
319
3200
    if (empty($valid_links)) {
3210
      return [];
322
    }
323
324
    // If only one link and format is 'link', render as single link.
3250
    if (count($valid_links) === 1 && $render_format === 'link') {
3260
      return $this->renderSingleLink($valid_links[0]);
327
    }
328
329
    // Render based on format.
330
    switch ($render_format) {
3310
      case 'radio':
3320
        return $this->renderRadioButtons($valid_links);
333
3340
      case 'checkboxes':
3350
        return $this->renderCheckboxes($valid_links);
336
3370
      case 'list':
3380
        return $this->renderUnorderedList($valid_links);
339
3400
      case 'link':
341
      default:
3420
        return $this->renderUnorderedList($valid_links);
343
    }
344
  }
345
346
  /**
347
   * Renders a single display link.
348
   *
349
   * @param array $link
350
   *   The link configuration.
351
   *
352
   * @return array
353
   *   The render array for a single link.
354
   */
355
  protected function renderSingleLink(array $link): array {
3560
    $label = (string) $link['label'];
3570
    $display_id = (string) $link['display_id'];
358
359
    // Get query parameters from the exposed input and pager.
3600
    $query = $this->view->getExposedInput();
3610
    if ($current_page = $this->view->getCurrentPage()) {
3620
      $query['page'] = $current_page;
363
    }
364
365
    // @todo Remove this parsing once these are removed from the request in
366
    //   https://www.drupal.org/node/2504709.
3670
    foreach ([
3680
      'view_name',
3690
      'view_display_id',
3700
      'view_args',
3710
      'view_path',
3720
      'view_dom_id',
3730
      'pager_element',
3740
      'view_base_path',
3750
      AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER,
3760
      FormBuilderInterface::AJAX_FORM_REQUEST,
3770
      MainContentViewSubscriber::WRAPPER_FORMAT,
3780
    ] as $key) {
3790
      unset($query[$key]);
380
    }
381
3820
    $storage_id = $this->view->storage->id();
383
384
    // Set default classes.
3850
    $classes = [
3860
      'views-display-link',
3870
      'views-display-link-' . $display_id,
3880
    ];
3890
    if ($display_id === $this->view->current_display) {
3900
      $classes[] = 'is-active';
391
    }
3920
    $classes[] = 'use-ajax';
393
3940
    $path = 'internal:/admin/visitors/_report/' . $storage_id . '/' . $display_id;
3950
    $query_class = '.view-id-' . $storage_id . '.view-display-id-' . $this->view->current_display;
396
3970
    $query_params = ['class' => $query_class];
398
3990
    return [
4000
      '#type' => 'link',
4010
      '#title' => $label,
4020
      '#url' => Url::fromUri($path, [
4030
        'query' => $query_params,
4040
      ]),
4050
      '#options' => [
4060
        'attributes' => ['class' => $classes],
4070
      ],
408
      // The use-ajax class only intercepts the click when this library is
409
      // present. Report pages do not load it on their own.
4100
      '#attached' => [
4110
        'library' => [
4120
          'core/drupal.ajax',
4130
        ],
4140
      ],
4150
    ];
416
  }
417
418
  /**
419
   * Renders display links as radio buttons.
420
   *
421
   * @param array $links
422
   *   Array of link configurations.
423
   *
424
   * @return array
425
   *   The render array for radio buttons.
426
   */
427
  protected function renderRadioButtons(array $links): array {
4280
    $options = [];
4290
    $default_value = NULL;
430
4310
    foreach ($links as $link) {
4320
      $display_id = (string) $link['display_id'];
4330
      $label = (string) $link['label'];
434
4350
      $options[$display_id] = $label;
436
4370
      if ($display_id === $this->view->current_display) {
4380
        $default_value = $display_id;
439
      }
440
    }
441
4420
    return [
4430
      '#type' => 'radios',
4440
      '#title' => $this->t('Display Options'),
4450
      '#options' => $options,
4460
      '#default_value' => $default_value,
4470
      '#attributes' => [
4480
        'class' => ['visitors-display-radios'],
4490
        'data-ajax' => 'true',
4500
      ],
4510
      '#ajax' => [
4520
        'callback' => [$this, 'ajaxDisplayChange'],
4530
        'wrapper' => 'visitors-display-content',
4540
      ],
4550
    ];
456
  }
457
458
  /**
459
   * Renders display links as checkboxes.
460
   *
461
   * @param array $links
462
   *   Array of link configurations.
463
   *
464
   * @return array
465
   *   The render array for checkboxes.
466
   */
467
  protected function renderCheckboxes(array $links): array {
4680
    $options = [];
4690
    $default_value = [];
470
4710
    foreach ($links as $link) {
4720
      $display_id = (string) $link['display_id'];
4730
      $label = (string) $link['label'];
474
4750
      $options[$display_id] = $label;
476
4770
      if ($display_id === $this->view->current_display) {
4780
        $default_value[] = $display_id;
479
      }
480
    }
481
4820
    return [
4830
      '#type' => 'checkboxes',
4840
      '#title' => $this->t('Display Options'),
4850
      '#options' => $options,
4860
      '#default_value' => $default_value,
4870
      '#attributes' => [
4880
        'class' => ['visitors-display-checkboxes'],
4890
        'data-ajax' => 'true',
4900
      ],
4910
      '#ajax' => [
4920
        'callback' => [$this, 'ajaxDisplayChange'],
4930
        'wrapper' => 'visitors-display-content',
4940
      ],
4950
    ];
496
  }
497
498
  /**
499
   * Renders display links as an unordered list.
500
   *
501
   * @param array $links
502
   *   Array of link configurations.
503
   *
504
   * @return array
505
   *   The render array for an unordered list.
506
   */
507
  protected function renderUnorderedList(array $links): array {
5080
    $items = [];
509
5100
    foreach ($links as $link) {
5110
      $items[] = $this->renderSingleLink($link);
512
    }
513
5140
    return [
5150
      '#theme' => 'item_list',
5160
      '#items' => $items,
5170
      '#attributes' => [
5180
        'class' => ['visitors-display-links'],
5190
      ],
5200
    ];
521
  }
522
523
  /**
524
   * AJAX callback for display change.
525
   *
526
   * @param array $form
527
   *   The form array.
528
   * @param \Drupal\Core\Form\FormStateInterface $form_state
529
   *   The form state.
530
   *
531
   * @return array
532
   *   The AJAX response.
533
   */
534
  public function ajaxDisplayChange(array &$form, FormStateInterface $form_state) {
535
    // This would need to be implemented based on specific requirements
536
    // for handling display changes via AJAX.
5370
    return [];
538
  }
539
540
}