You are here

EntityViewEventSubscriber.php in Better Statistics 8

File

src/EventSubscriber/EntityViewEventSubscriber.php
View source
<?php

namespace Drupal\better_statistics\EventSubscriber;

use Drupal\better_statistics\EntityInteractionCollector;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\Session\AccountProxy;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class EntityViewEventSubscriber.
 *
 * @package Drupal\better_statistics
 */
class EntityViewEventSubscriber implements EventSubscriberInterface {

  /**
   * Defines type of action that can be used.
   *
   * @constant for what entity interaction "action" is used for view
   */
  const ACTION_VIEW = "View";

  /**
   * Drupal\Core\Routing\CurrentRouteMatch definition.
   *
   * @var \Drupal\Core\Routing\CurrentRouteMatch
   */
  protected $currentRouteMatch;

  /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
  protected $currentUser;

  /**
   * Drupal\better_statistics\.
   *
   * @var \Drupal\better_statistics\EntityInteractionCollector
   */
  protected $entityInteractionCollector;

  /**
   * Constructor.
   */
  public function __construct(CurrentRouteMatch $currentRouteMatch, AccountProxy $currentUser, EntityInteractionCollector $entityInteractionCollector) {
    $this->currentRouteMatch = $currentRouteMatch;
    $this->currentUser = $currentUser;
    $this->entityInteractionCollector = $entityInteractionCollector;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {

    // Priority is set to 1 to avoid this listener from being stopped by other
    // listeners.
    // @see ContainerAwareEventDispatcher::dispatch()
    $events[KernelEvents::VIEW][] = [
      'onEventView',
      1,
    ];
    return $events;
  }

  /**
   * Triggering method for entity view routes.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent $event
   *   Event that called action.
   */
  public function onEventView(GetResponseForControllerResultEvent $event) {
    try {
      if (preg_match('/entity\\.([\\w]+)\\.canonical/', $this->currentRouteMatch
        ->getRouteName(), $matches)) {

        /** @var \Drupal\Core\Entity\EntityInterface $entity */
        $entity = $this->currentRouteMatch
          ->getParameter($matches[1]);

        // Pass the interaction to the collector.
        $this->entityInteractionCollector
          ->actionTypeTrigger($entity, $this->currentUser, self::ACTION_VIEW);
      }
    } catch (\Exception $e) {
      watchdog_exception('better_statistics', $e);
    }
  }

}

Classes

Namesort descending Description
EntityViewEventSubscriber Class EntityViewEventSubscriber.