Coverage index

src/Service/EventService.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Service;
6
7
use Drupal\Component\Datetime\TimeInterface;
8
use Drupal\Component\Utility\Unicode;
9
use Drupal\Core\Database\Connection;
10
use Drupal\visitors\VisitorsCookieInterface;
11
use Drupal\visitors\VisitorsEventInterface;
12
use Drupal\visitors\VisitorsTrackerInterface;
13
14
/**
15
 * Queues browser events and writes events PHP already knows about.
16
 */
17
final class EventService implements VisitorsEventInterface {
18
19
  /**
20
   * Page columns copied from the latest page view.
21
   */
22
  private const PAGE_COLUMNS = [
23
    'page_view',
24
    'title',
25
    'uid',
26
    'url_prefix',
27
    'url',
28
    'path',
29
    'route',
30
    'referrer_url',
31
    'referrer_url_prefix',
32
    'referrer_internal',
33
    'referrer_path',
34
    'referrer_route',
35
    'server',
36
  ];
37
38
  /**
39
   * Events queued for the browser tracker.
40
   *
41
   * @var array<int, array<string, float|string>>
42
   */
43
  protected array $queue = [];
44
45
  /**
46
   * Constructs an EventService.
47
   *
48
   * @param \Drupal\Core\Database\Connection $database
49
   *   The database connection.
50
   * @param \Drupal\visitors\VisitorsTrackerInterface $tracker
51
   *   The visit and event tracker.
52
   * @param \Drupal\visitors\VisitorsCookieInterface $cookie
53
   *   The visitor cookie.
54
   * @param \Drupal\Component\Datetime\TimeInterface $time
55
   *   The time service.
56
   */
57
  public function __construct(
58
    protected Connection $database,
59
    protected VisitorsTrackerInterface $tracker,
60
    protected VisitorsCookieInterface $cookie,
61
    protected TimeInterface $time,
623
  ) {}
63
64
  /**
65
   * {@inheritdoc}
66
   */
67
  public function trackEvent(string $category, string $action, ?string $name = NULL, ?float $value = NULL): void {
681
    $category = $this->eventString($category);
691
    $action = $this->eventString($action);
701
    if ($category === '' || $action === '') {
711
      return;
72
    }
73
741
    $item = [
751
      'category' => $category,
761
      'action' => $action,
771
      'name' => $this->eventString($name),
781
    ];
791
    if ($value !== NULL) {
801
      $item['value'] = $value;
81
    }
821
    $this->queue[] = $item;
83
  }
84
85
  /**
86
   * {@inheritdoc}
87
   */
88
  public function getQueuedEvents(): array {
891
    return $this->queue;
90
  }
91
92
  /**
93
   * {@inheritdoc}
94
   */
95
  public function record(string $category, string $action, ?string $name = NULL, ?float $value = NULL): ?int {
962
    $category = $this->eventString($category);
972
    $action = $this->eventString($action);
982
    if ($category === '' || $action === '') {
991
      return NULL;
100
    }
101
1022
    $visitor_id = $this->cookie->getId();
1032
    if ($visitor_id === NULL || $visitor_id === '') {
1041
      return NULL;
105
    }
106
1072
    $request_time = $this->time->getRequestTime();
1082
    $visit = $this->openVisit($visitor_id, $request_time);
1092
    if ($visit === NULL) {
1101
      return NULL;
111
    }
112
1131
    $page = $this->latestPageView((int) $visit['id']);
1141
    $stored_name = $this->eventString($name);
1151
    $fields = [
1161
      'visit_id' => (int) $visit['id'],
1171
      'created' => $request_time,
1181
      'event_category' => $category,
1191
      'event_action' => $action,
1201
      'event_name' => $stored_name === '' ? NULL : $stored_name,
1211
      'event_value' => $value,
1221
      'title' => '',
1231
      'url' => '',
1241
      'path' => '',
1251
      'route' => '',
1261
      'referrer_url' => '',
1271
      'referrer_internal' => 0,
1281
      'referrer_path' => '',
1291
      'referrer_route' => '',
1301
    ];
1311
    foreach (self::PAGE_COLUMNS as $column) {
1321
      if ($page !== NULL && array_key_exists($column, $page)) {
1331
        $fields[$column] = $page[$column];
134
      }
135
    }
136
1371
    $event_id = $this->tracker->writeEvent($fields);
1381
    $uid = isset($visit['uid']) && $visit['uid'] !== '' ? (string) $visit['uid'] : NULL;
1391
    $this->tracker->updateVisit(
1401
      (int) $visit['id'],
1411
      $event_id,
1421
      $request_time,
1431
      $uid,
1441
      FALSE,
1451
    );
146
1471
    return $event_id;
148
  }
149
150
  /**
151
   * The open visit for this visitor.
152
   *
153
   * @param string $visitor_id
154
   *   The visitor id from the cookie.
155
   * @param int $request_time
156
   *   The request time.
157
   *
158
   * @return array<string, mixed>|null
159
   *   The visit id and user id, or NULL.
160
   */
161
  protected function openVisit(string $visitor_id, int $request_time): ?array {
1622
    $ago = $request_time - VisitorsTrackerInterface::SESSION_TIMEOUT;
1632
    $visit = $this->database->select('visitors_visit', 'vv')
1642
      ->fields('vv', ['id', 'uid'])
1652
      ->condition('vv.visitor_id', $visitor_id)
1662
      ->condition('vv.exit_time', $ago, '>')
1672
      ->orderBy('vv.exit_time', 'DESC')
1682
      ->range(0, 1)
1692
      ->execute()
1702
      ->fetchAssoc();
171
1722
    return $visit === FALSE ? NULL : $visit;
173
  }
174
175
  /**
176
   * The latest page view on a visit.
177
   *
178
   * Downloads, outlinks, and custom events are not page views.
179
   *
180
   * @param int $visit_id
181
   *   The visit id.
182
   *
183
   * @return array<string, mixed>|null
184
   *   The page-view columns, or NULL.
185
   */
186
  protected function latestPageView(int $visit_id): ?array {
1871
    $query = $this->database->select('visitors_event', 've');
1881
    $query->fields('ve', self::PAGE_COLUMNS);
1891
    $query->condition('ve.visit_id', $visit_id);
1901
    $query->isNull('ve.event_category');
1911
    $query->condition($query->orConditionGroup()
1921
      ->isNull('ve.event')
1931
      ->condition('ve.event', ['download', 'outlink'], 'NOT IN'));
1941
    $query->orderBy('ve.id', 'DESC');
1951
    $query->range(0, 1);
1961
    $page = $query->execute()->fetchAssoc();
197
1981
    return $page === FALSE ? NULL : $page;
199
  }
200
201
  /**
202
   * Trims and cuts an event string to the column length.
203
   *
204
   * @param string|null $value
205
   *   The event string.
206
   *
207
   * @return string
208
   *   The stored string, or an empty string when the value is blank.
209
   */
210
  protected function eventString(?string $value): string {
2113
    $value = trim((string) $value);
2123
    if ($value === '') {
2132
      return '';
214
    }
2153
    return Unicode::truncate($value, 255, FALSE, FALSE);
216
  }
217
218
}