Coverage index

src/Plugin/Block/VisitorsPopularBlock.php

Lines: 99.07%

LineHitsSource
1
<?php
2
3
namespace Drupal\visitors\Plugin\Block;
4
5
use Drupal\Core\Access\AccessResult;
6
use Drupal\Core\Block\Attribute\Block;
7
use Drupal\Core\Block\BlockBase;
8
use Drupal\Core\Config\ConfigFactoryInterface;
9
use Drupal\Core\Entity\EntityRepositoryInterface;
10
use Drupal\Core\Entity\EntityTypeManagerInterface;
11
use Drupal\Core\Form\FormStateInterface;
12
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
13
use Drupal\Core\Render\RendererInterface;
14
use Drupal\Core\Session\AccountInterface;
15
use Drupal\Core\StringTranslation\TranslatableMarkup;
16
use Drupal\visitors\VisitorsCounterInterface;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18
19
/**
20
 * Provides a 'Popular content' block.
21
 */
22
#[Block(
23
  id: "visitors_popular_block",
24
  admin_label: new TranslatableMarkup("Popular content")
25
)]
26
final class VisitorsPopularBlock extends BlockBase implements ContainerFactoryPluginInterface {
27
28
  /**
29
   * The entity type manager.
30
   *
31
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
32
   */
33
  protected $entityTypeManager;
34
35
  /**
36
   * The entity repository service.
37
   *
38
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
39
   */
40
  protected $entityRepository;
41
42
  /**
43
   * The storage for visitor counter.
44
   *
45
   * @var \Drupal\visitors\VisitorsCounterInterface
46
   */
47
  protected $statisticsStorage;
48
49
  /**
50
   * The renderer interface.
51
   *
52
   * @var \Drupal\Core\Render\RendererInterface
53
   */
54
  protected $renderer;
55
56
  /**
57
   * The configuration factory.
58
   *
59
   * @var \Drupal\Core\Config\ConfigFactoryInterface
60
   */
61
  protected $configFactory;
62
63
  /**
64
   * Constructs a StatisticsPopularBlock object.
65
   *
66
   * @param array $configuration
67
   *   A configuration array containing information about the plugin instance.
68
   * @param string $plugin_id
69
   *   The plugin_id for the plugin instance.
70
   * @param mixed $plugin_definition
71
   *   The plugin implementation definition.
72
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
73
   *   The entity type manager.
74
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
75
   *   The entity repository service.
76
   * @param \Drupal\visitors\VisitorsCounterInterface $statistics_storage
77
   *   The storage for statistics.
78
   * @param \Drupal\Core\Render\RendererInterface $renderer
79
   *   The renderer configuration array.
80
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
81
   *   The configuration factory.
82
   */
83
  public function __construct(
84
    array $configuration,
85
    $plugin_id,
86
    $plugin_definition,
87
    EntityTypeManagerInterface $entity_type_manager,
88
    EntityRepositoryInterface $entity_repository,
89
    VisitorsCounterInterface $statistics_storage,
90
    RendererInterface $renderer,
91
    ConfigFactoryInterface $config_factory,
92
  ) {
9311
    parent::__construct($configuration, $plugin_id, $plugin_definition);
9411
    $this->entityTypeManager = $entity_type_manager;
9511
    $this->entityRepository = $entity_repository;
9611
    $this->statisticsStorage = $statistics_storage;
9711
    $this->renderer = $renderer;
9811
    $this->configFactory = $config_factory;
99
  }
100
101
  /**
102
   * {@inheritdoc}
103
   */
104
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
10511
    return new self(
10611
      $configuration,
10711
      $plugin_id,
10811
      $plugin_definition,
10911
      $container->get('entity_type.manager'),
11011
      $container->get('entity.repository'),
11111
      $container->get('visitors.counter'),
11211
      $container->get('renderer'),
11311
      $container->get('config.factory'),
11411
    );
115
  }
116
117
  /**
118
   * {@inheritdoc}
119
   */
120
  public function defaultConfiguration() {
12111
    return [
12211
      'top_day_num' => 0,
12311
      'top_all_num' => 0,
12411
      'top_last_num' => 0,
12511
      'entity_type' => 'node',
12611
    ];
127
  }
128
129
  /**
130
   * {@inheritdoc}
131
   */
132
  protected function blockAccess(AccountInterface $account) {
1334
    $settings = $this->configFactory->get('visitors.settings');
1344
    $entity_type = $this->configuration['entity_type'] ?? '';
1354
    $allowed_entity_types = $settings->get('counter.entity_types');
1364
    $disabled_or_entity_type_not_allowed = !$settings->get('counter.enabled') || !in_array($entity_type, $allowed_entity_types);
1374
    if ($disabled_or_entity_type_not_allowed) {
1382
      return AccessResult::forbidden();
139
    }
140
1412
    return AccessResult::allowedIfHasPermission($account, 'access content');
142
  }
143
144
  /**
145
   * {@inheritdoc}
146
   */
147
  public function blockForm($form, FormStateInterface $form_state) {
148
    // Popular content block settings.
1491
    $numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40];
1501
    $numbers = ['0' => $this->t('Disabled')] + array_combine($numbers, $numbers);
1511
    $form['statistics_block_top_day_num'] = [
1521
      '#type' => 'select',
1531
      '#title' => $this->t("Number of day's top views to display"),
1541
      '#default_value' => $this->configuration['top_day_num'],
1551
      '#options' => $numbers,
1561
      '#description' => $this->t('How many content items to display in "day" list.'),
1571
    ];
1581
    $form['statistics_block_top_all_num'] = [
1591
      '#type' => 'select',
1601
      '#title' => $this->t('Number of all time views to display'),
1611
      '#default_value' => $this->configuration['top_all_num'],
1621
      '#options' => $numbers,
1631
      '#description' => $this->t('How many content items to display in "all time" list.'),
1641
    ];
1651
    $form['statistics_block_top_last_num'] = [
1661
      '#type' => 'select',
1671
      '#title' => $this->t('Number of most recent views to display'),
1681
      '#default_value' => $this->configuration['top_last_num'],
1691
      '#options' => $numbers,
1701
      '#description' => $this->t('How many content items to display in "recently viewed" list.'),
1711
    ];
1721
    $form['entity_type'] = [
1731
      '#type' => 'radios',
1741
      '#title' => $this->t('Entity types'),
1751
      '#options' => $this->entityTypes(),
1761
      '#default_value' => $this->configuration['entity_type'] ?? 'node',
1771
      '#description' => $this->t('Select entity types to display popular content.'),
1781
    ];
179
1801
    return $form;
181
  }
182
183
  /**
184
   * Returns a list of entity types.
185
   */
186
  protected function entityTypes() {
1871
    $allowed_entity_types = $this->configFactory->get('visitors.settings')->get('counter.entity_types');
1881
    $entity_types_list = [];
1891
    $entity_definitions = $this->entityTypeManager->getDefinitions();
1901
    foreach ($entity_definitions as $entity_name => $entity_definition) {
1911
      if (!in_array($entity_name, $allowed_entity_types)) {
1920
        continue;
193
      }
1941
      $entity_types_list[$entity_name] = (string) $entity_definition->getLabel();
195
    }
1961
    asort($entity_types_list);
197
1981
    return $entity_types_list;
199
  }
200
201
  /**
202
   * {@inheritdoc}
203
   */
204
  public function blockSubmit($form, FormStateInterface $form_state) {
2051
    $this->configuration['top_day_num'] = $form_state->getValue('statistics_block_top_day_num');
2061
    $this->configuration['top_all_num'] = $form_state->getValue('statistics_block_top_all_num');
2071
    $this->configuration['top_last_num'] = $form_state->getValue('statistics_block_top_last_num');
2081
    $this->configuration['entity_type'] = $form_state->getValue('entity_type');
209
  }
210
211
  /**
212
   * {@inheritdoc}
213
   */
214
  public function build() {
2151
    $content = [];
2161
    $entity_type = $this->configuration['entity_type'] ?? 'node';
2171
    if ($this->configuration['top_day_num'] > 0) {
2181
      $ids = $this->statisticsStorage->fetchAll($entity_type, 'today', $this->configuration['top_day_num']);
2191
      if ($ids) {
2201
        $content['top_day'] = $this->entityLabelList($ids, $this->t("Today's:"));
2211
        $content['top_day']['#suffix'] = '<br />';
222
      }
223
    }
224
2251
    if ($this->configuration['top_all_num'] > 0) {
2261
      $ids = $this->statisticsStorage->fetchAll($entity_type, 'total', $this->configuration['top_all_num']);
2271
      if ($ids) {
2281
        $content['top_all'] = $this->entityLabelList($ids, $this->t('All time:'));
2291
        $content['top_all']['#suffix'] = '<br />';
230
      }
231
    }
232
2331
    if ($this->configuration['top_last_num'] > 0) {
2341
      $ids = $this->statisticsStorage->fetchAll($entity_type, 'timestamp', $this->configuration['top_last_num']);
2351
      $content['top_last'] = $this->entityLabelList($ids, $this->t('Last viewed:'));
2361
      $content['top_last']['#suffix'] = '<br />';
237
    }
238
2391
    return $content;
240
  }
241
242
  /**
243
   * {@inheritdoc}
244
   */
245
  public function getCacheTags() {
2461
    return ['config:visitors.settings'];
247
  }
248
249
  /**
250
   * Generates the ordered array of entity links for build().
251
   *
252
   * @param int[] $ids
253
   *   An ordered array of entity ids.
254
   * @param string $title
255
   *   The title for the list.
256
   *
257
   * @return array
258
   *   A render array for the list.
259
   */
260
  protected function entityLabelList(array $ids, $title) {
2611
    $entity_type = $this->configuration['entity_type'] ?? 'node';
2621
    $entities = $this->entityTypeManager->getStorage($entity_type)->loadMultiple($ids);
263
2641
    $items = [];
2651
    foreach ($ids as $id) {
2661
      $entity = $this->entityRepository->getTranslationFromContext($entities[$id]);
2671
      $item = $entity->toLink()->toRenderable();
2681
      $this->renderer->addCacheableDependency($item, $entity);
2691
      $items[] = $item;
270
    }
271
2721
    return [
2731
      '#theme' => 'item_list',
2741
      '#items' => $items,
2751
      '#title' => $title,
2761
      '#cache' => [
2771
        'tags' => $this->entityTypeManager->getDefinition($entity_type)->getListCacheTags(),
2781
      ],
2791
    ];
280
  }
281
282
}