public function NodeViewSubscriber::trackNodeView in Open Social 8.9
Same name and namespace in other branches
- 8.4 modules/custom/social_node_statistics/src/EventSubscriber/NodeViewSubscriber.php \Drupal\social_node_statistics\EventSubscriber\NodeViewSubscriber::trackNodeView()
- 8.5 modules/custom/social_node_statistics/src/EventSubscriber/NodeViewSubscriber.php \Drupal\social_node_statistics\EventSubscriber\NodeViewSubscriber::trackNodeView()
- 8.6 modules/custom/social_node_statistics/src/EventSubscriber/NodeViewSubscriber.php \Drupal\social_node_statistics\EventSubscriber\NodeViewSubscriber::trackNodeView()
- 8.7 modules/custom/social_node_statistics/src/EventSubscriber/NodeViewSubscriber.php \Drupal\social_node_statistics\EventSubscriber\NodeViewSubscriber::trackNodeView()
- 8.8 modules/custom/social_node_statistics/src/EventSubscriber/NodeViewSubscriber.php \Drupal\social_node_statistics\EventSubscriber\NodeViewSubscriber::trackNodeView()
This method is called when the KernelEvents::TERMINATE event is dispatched.
Parameters
\Symfony\Component\HttpKernel\Event\PostResponseEvent $event: The event.
Throws
\Exception
File
- modules/
custom/ social_node_statistics/ src/ EventSubscriber/ NodeViewSubscriber.php, line 88
Class
- NodeViewSubscriber
- Class NodeViewSubscriber.
Namespace
Drupal\social_node_statistics\EventSubscriberCode
public function trackNodeView(PostResponseEvent $event) {
// If the response is a success (e.g. status code 200) we can proceed.
if ($event
->getResponse()
->isSuccessful()) {
// Check if we're on a node page.
if ($this->routeMatcher
->getRouteName() === 'entity.node.canonical') {
$node = $this->routeMatcher
->getParameter('node');
if ($node instanceof NodeInterface) {
$config = \Drupal::config('social_node_statistics.settings');
// Check if we should log for this node bundle.
if (in_array($node
->bundle(), $config
->get('node_types'), FALSE)) {
$now = $this->time
->getRequestTime();
// Insert the event in the table.
$this->database
->insert('node_statistics')
->fields([
'uid' => $this->account
->id(),
'nid' => $node
->id(),
'timestamp' => $now,
])
->execute();
// Get latest timestamp for possible cache invalidation.
$latest = $this->database
->select('node_statistics', 'n')
->fields('n', [
'timestamp',
])
->condition('n.nid', $node
->id())
->orderBy('n.timestamp', 'DESC')
->range('1', '1')
->execute()
->fetchField();
// Get count of views for possible cache invalidation.
$count = $this->database
->select('node_statistics', 'n')
->condition('n.nid', $node
->id())
->countQuery()
->execute()
->fetchField();
// Clear render cache only if max age is reached and the count is of
// a certain predefined number.
if ($now - $latest >= $config
->get('max_age') && $count % $config
->get('min_views') === 0) {
Cache::invalidateTags([
'node:' . $node
->id() . ':views_count',
]);
}
}
}
}
}
}