Coverage index

src/Plugin/views/area/VisitorsDisplayLink.php

Lines: 94.12%

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) {
4325
    parent::__construct($configuration, $plugin_id, $plugin_definition);
4425
    $this->viewSettings = $view_settings;
45
  }
46
47
  /**
48
   * {@inheritdoc}
49
   */
50
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
5125
    return new self(
5225
      $configuration,
5325
      $plugin_id,
5425
      $plugin_definition,
5525
      $container->get('config.factory')->get('views.settings')
5625
    );
57
  }
58
59
  /**
60
   * {@inheritdoc}
61
   */
62
  protected function defineOptions() {
6325
    $options = parent::defineOptions();
6425
    $options['display_links'] = ['default' => []];
6525
    $options['render_format'] = ['default' => 'link'];
6625
    return $options;
67
  }
68
69
  /**
70
   * {@inheritdoc}
71
   */
72
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
731
    parent::buildOptionsForm($form, $form_state);
74
751
    $allowed_displays = [];
761
    $displays = $this->view->storage->get('display');
771
    foreach ($displays as $display_id => $display) {
781
      if ($this->isPathBasedDisplay($display_id)) {
791
        unset($displays[$display_id]);
801
        continue;
81
      }
821
      $allowed_displays[$display_id] = $display['display_title'];
83
    }
84
851
    $form['description'] = [
861
      [
871
        '#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:'),
881
      ],
891
      [
901
        '#theme' => 'item_list',
911
        '#items' => [
921
          $this->t('Has a path.'),
931
          $this->t('Has the same filter criteria.'),
941
          $this->t('Has the same sort criteria.'),
951
          $this->t('Has the same contextual filters.'),
961
        ],
971
      ],
981
    ];
99
1001
    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.
1071
      $form['render_format'] = [
1081
        '#title' => $this->t('Render format'),
1091
        '#type' => 'select',
1101
        '#options' => [
1111
          'link' => $this->t('Single link (if only one display)'),
1121
          'radio' => $this->t('Radio buttons'),
1131
          'checkboxes' => $this->t('Checkboxes'),
1141
          'list' => $this->t('Unordered list of links'),
1151
        ],
1161
        '#default_value' => (string) ($this->options['render_format'] ?? 'link'),
1171
        '#description' => $this->t('Choose how to render the display links.'),
1181
      ];
119
120
      // Display links configuration.
1211
      $form['display_links'] = [
1221
        '#type' => 'fieldset',
1231
        '#title' => $this->t('Display Links'),
1241
        '#description' => $this->t('Configure multiple display links. Each link can have its own label.'),
1251
        '#tree' => TRUE,
1261
      ];
127
1281
      $display_links = $this->options['display_links'] ?? [];
1291
      if (empty($display_links)) {
130
        // Initialize with one empty link if none exist.
1311
        $display_links = [['display_id' => '', 'label' => '']];
132
      }
133
      else {
134
        // Always add an empty link at the end for adding new ones.
1351
        $display_links[] = ['display_id' => '', 'label' => ''];
136
      }
137
1381
      $total_links = count($display_links);
1391
      foreach ($display_links as $index => $link) {
140
        // Ensure we have a valid array structure.
1411
        if (!is_array($link)) {
142
          continue;
143
        }
144
1451
        $is_empty = empty((string) ($link['display_id'] ?? '')) && empty((string) ($link['label'] ?? ''));
1461
        $is_last = ($index === $total_links - 1);
147
1481
        $form['display_links'][$index] = [
1491
          '#type' => 'fieldset',
1501
          '#title' => $is_empty ? $this->t('Add new link') : $this->t('Link @index', ['@index' => (int) $index + 1]),
1511
          '#collapsible' => TRUE,
1521
          '#collapsed' => $is_empty ? FALSE : ($index > 0),
1531
        ];
154
1551
        $form['display_links'][$index]['display_id'] = [
1561
          '#title' => $this->t('Display'),
1571
          '#type' => 'select',
1581
          '#options' => ['' => $this->t('- Select -')] + $allowed_displays,
1591
          '#default_value' => (string) ($link['display_id'] ?? ''),
1601
          '#required' => !$is_empty,
1611
        ];
162
1631
        $form['display_links'][$index]['label'] = [
1641
          '#title' => $this->t('Label'),
1651
          '#description' => $this->t('The text of the link.'),
1661
          '#type' => 'textfield',
1671
          '#default_value' => (string) ($link['label'] ?? ''),
1681
          '#required' => !$is_empty,
1691
        ];
170
171
        // Only show remove button for non-empty links that are not the last
172
        // one.
1731
        if (!$is_empty && !$is_last) {
1741
          $form['display_links'][$index]['remove'] = [
1751
            '#type' => 'submit',
1761
            '#value' => $this->t('Remove'),
1771
            '#name' => 'remove_link_' . $index,
1781
            '#submit' => [[$this, 'removeDisplayLink']],
1791
          ];
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) {
1901
    $triggering_element = $form_state->getTriggeringElement();
1911
    $index = (int) str_replace('remove_link_', '', $triggering_element['#name']);
192
1931
    $display_links = $form_state->getValue('display_links', []);
1941
    unset($display_links[$index]);
195
    // Re-index array.
1961
    $display_links = array_values($display_links);
1971
    $form_state->setValue('display_links', $display_links);
1981
    $form_state->setRebuild();
199
  }
200
201
  /**
202
   * {@inheritdoc}
203
   */
204
  public function validate() {
2051
    $errors = [];
206
207
    // Do not add errors for the default display if it is not displayed in the
208
    // UI.
2091
    if ($this->displayHandler->isDefaultDisplay() && !$this->viewSettings->get('ui.show.default_display')) {
2100
      return $errors;
211
    }
212
213
    // Validate new display links configuration.
2141
    $display_links = $this->options['display_links'] ?? [];
2151
    if (!empty($display_links)) {
2161
      foreach ($display_links as $index => $link) {
217
        // Ensure we have valid array structure and convert values to strings.
2181
        if (!is_array($link) || empty($link['display_id']) || empty($link['label'])) {
219
          // Skip empty links.
220
          continue;
221
        }
222
2231
        $linked_display_id = (string) $link['display_id'];
2241
        $link_label = (string) $link['label'];
225
226
        // Check if the linked display hasn't been removed.
2271
        if (!$this->view->displayHandlers->get($linked_display_id)) {
2281
          $errors[] = $this->t('%current_display: Link @index in the %area area points to the %linked_display display which no longer exists.', [
2291
            '%current_display' => $this->displayHandler->display['display_title'],
2301
            '@index' => $index + 1,
2311
            '%area' => $this->areaType,
2321
            '%linked_display' => $linked_display_id,
2331
          ]);
2341
          continue;
235
        }
236
237
        // Check if the linked display is a path-based display.
2381
        if ($this->isPathBasedDisplay($linked_display_id)) {
2391
          $errors[] = $this->t('%current_display: Link @index in the %area area points to the %linked_display display which does not have a path.', [
2401
            '%current_display' => $this->displayHandler->display['display_title'],
2411
            '@index' => $index + 1,
2421
            '%area' => $this->areaType,
2431
            '%linked_display' => $this->view->displayHandlers->get($linked_display_id)->display['display_title'],
2441
          ]);
2451
          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.
2521
        $unequal_options = [
2531
          'filters' => $this->t('Filter criteria'),
2541
          'arguments' => $this->t('Contextual filters'),
2551
        ];
2561
        foreach (array_keys($unequal_options) as $option) {
2571
          if ($this->hasEqualOptions($linked_display_id, $option)) {
2581
            unset($unequal_options[$option]);
259
          }
260
        }
261
2621
        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.
2751
      if (!empty($errors)) {
2761
        return $errors;
277
      }
278
    }
279
280
    // If no display links are configured at all, show an error.
2811
    if (empty($display_links)) {
2821
      $errors[] = $this->t('%current_display: The link in the %area area has no configured display.', [
2831
        '%current_display' => $this->displayHandler->display['display_title'],
2841
        '%area' => $this->areaType,
2851
      ]);
286
    }
287
2881
    return $errors;
289
  }
290
291
  /**
292
   * {@inheritdoc}
293
   */
294
  public function render($empty = FALSE) {
2951
    if ($empty && empty($this->options['empty'])) {
2961
      return [];
297
    }
298
299
    // Get display links configuration.
3001
    $display_links = $this->options['display_links'] ?? [];
3011
    $render_format = $this->options['render_format'] ?? 'link';
302
303
    // Filter out empty links.
3041
    $display_links = array_filter($display_links, function ($link) {
3051
      return is_array($link) && !empty($link['display_id']) && !empty($link['label']);
3061
    });
307
3081
    if (empty($display_links)) {
3090
      return [];
310
    }
311
312
    // Filter out path-based displays.
3131
    $valid_links = [];
3141
    foreach ($display_links as $link) {
3151
      if (!$this->isPathBasedDisplay($link['display_id'])) {
3161
        $valid_links[] = $link;
317
      }
318
    }
319
3201
    if (empty($valid_links)) {
3211
      return [];
322
    }
323
324
    // If only one link and format is 'link', render as single link.
3251
    if (count($valid_links) === 1 && $render_format === 'link') {
3261
      return $this->renderSingleLink($valid_links[0]);
327
    }
328
329
    // Render based on format.
330
    switch ($render_format) {
3311
      case 'radio':
3321
        return $this->renderRadioButtons($valid_links);
333
3341
      case 'checkboxes':
3351
        return $this->renderCheckboxes($valid_links);
336
3371
      case 'list':
3381
        return $this->renderUnorderedList($valid_links);
339
3401
      case 'link':
341
      default:
3421
        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 {
3561
    $label = (string) $link['label'];
3571
    $display_id = (string) $link['display_id'];
358
359
    // Get query parameters from the exposed input and pager.
3601
    $query = $this->view->getExposedInput();
3611
    if ($current_page = $this->view->getCurrentPage()) {
3621
      $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.
3671
    foreach ([
3681
      'view_name',
3691
      'view_display_id',
3701
      'view_args',
3711
      'view_path',
3721
      'view_dom_id',
3731
      'pager_element',
3741
      'view_base_path',
3751
      AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER,
3761
      FormBuilderInterface::AJAX_FORM_REQUEST,
3771
      MainContentViewSubscriber::WRAPPER_FORMAT,
3781
    ] as $key) {
3791
      unset($query[$key]);
380
    }
381
3821
    $storage_id = $this->view->storage->id();
383
384
    // Set default classes.
3851
    $classes = [
3861
      'views-display-link',
3871
      'views-display-link-' . $display_id,
3881
    ];
3891
    if ($display_id === $this->view->current_display) {
3900
      $classes[] = 'is-active';
391
    }
3921
    $classes[] = 'use-ajax';
393
3941
    $path = 'internal:/admin/visitors/_report/' . $storage_id . '/' . $display_id;
3951
    $query_class = '.view-id-' . $storage_id . '.view-display-id-' . $this->view->current_display;
396
3971
    $query_params = ['class' => $query_class];
398
3991
    return [
4001
      '#type' => 'link',
4011
      '#title' => $label,
4021
      '#url' => Url::fromUri($path, [
4031
        'query' => $query_params,
4041
      ]),
4051
      '#options' => [
4061
        'attributes' => ['class' => $classes],
4071
      ],
408
      // The use-ajax class only intercepts the click when this library is
409
      // present. Report pages do not load it on their own.
4101
      '#attached' => [
4111
        'library' => [
4121
          'core/drupal.ajax',
4131
        ],
4141
      ],
4151
    ];
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 {
4281
    $options = [];
4291
    $default_value = NULL;
430
4311
    foreach ($links as $link) {
4321
      $display_id = (string) $link['display_id'];
4331
      $label = (string) $link['label'];
434
4351
      $options[$display_id] = $label;
436
4371
      if ($display_id === $this->view->current_display) {
4380
        $default_value = $display_id;
439
      }
440
    }
441
4421
    return [
4431
      '#type' => 'radios',
4441
      '#title' => $this->t('Display Options'),
4451
      '#options' => $options,
4461
      '#default_value' => $default_value,
4471
      '#attributes' => [
4481
        'class' => ['visitors-display-radios'],
4491
        'data-ajax' => 'true',
4501
      ],
4511
      '#ajax' => [
4521
        'callback' => [$this, 'ajaxDisplayChange'],
4531
        'wrapper' => 'visitors-display-content',
4541
      ],
4551
    ];
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 {
4681
    $options = [];
4691
    $default_value = [];
470
4711
    foreach ($links as $link) {
4721
      $display_id = (string) $link['display_id'];
4731
      $label = (string) $link['label'];
474
4751
      $options[$display_id] = $label;
476
4771
      if ($display_id === $this->view->current_display) {
4780
        $default_value[] = $display_id;
479
      }
480
    }
481
4821
    return [
4831
      '#type' => 'checkboxes',
4841
      '#title' => $this->t('Display Options'),
4851
      '#options' => $options,
4861
      '#default_value' => $default_value,
4871
      '#attributes' => [
4881
        'class' => ['visitors-display-checkboxes'],
4891
        'data-ajax' => 'true',
4901
      ],
4911
      '#ajax' => [
4921
        'callback' => [$this, 'ajaxDisplayChange'],
4931
        'wrapper' => 'visitors-display-content',
4941
      ],
4951
    ];
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 {
5081
    $items = [];
509
5101
    foreach ($links as $link) {
5111
      $items[] = $this->renderSingleLink($link);
512
    }
513
5141
    return [
5151
      '#theme' => 'item_list',
5161
      '#items' => $items,
5171
      '#attributes' => [
5181
        'class' => ['visitors-display-links'],
5191
      ],
5201
    ];
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.
5371
    return [];
538
  }
539
540
}