Coverage index

src/Plugin/VisitorsSiteSearchBase.php

Lines: 50.00%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Plugin;
6
7
use Drupal\Component\Plugin\PluginBase;
8
use Drupal\visitors\VisitorsSiteSearchInterface;
9
use Symfony\Component\DependencyInjection\ContainerInterface;
10
use Symfony\Component\HttpFoundation\RequestStack;
11
12
/**
13
 * Shared result-count lookup for site search detectors.
14
 */
15
abstract class VisitorsSiteSearchBase extends PluginBase implements VisitorsSiteSearchInterface {
16
17
  /**
18
   * Constructs a site search detector.
19
   *
20
   * @param array $configuration
21
   *   A configuration array containing information about the plugin instance.
22
   * @param string $plugin_id
23
   *   The plugin ID for the plugin instance.
24
   * @param mixed $plugin_definition
25
   *   The plugin implementation definition.
26
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
27
   *   The request stack.
28
   */
29
  public function __construct(
30
    array $configuration,
31
    $plugin_id,
32
    $plugin_definition,
33
    protected RequestStack $requestStack,
34
  ) {
3511
    parent::__construct($configuration, $plugin_id, $plugin_definition);
36
  }
37
38
  /**
39
   * {@inheritdoc}
40
   */
41
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
4211
    return new static(
4311
      $configuration,
4411
      $plugin_id,
4511
      $plugin_definition,
4611
      $container->get('request_stack'),
4711
    );
48
  }
49
50
  /**
51
   * {@inheritdoc}
52
   */
53
  public function resultCount(): ?int {
540
    $request = $this->requestStack->getCurrentRequest();
550
    if ($request === NULL) {
560
      return NULL;
57
    }
580
    $count = $request->attributes->get('visitors_search_count');
590
    if (!is_numeric($count) || (int) $count < 0) {
600
      return NULL;
61
    }
620
    return (int) $count;
63
  }
64
65
}