1

Tripped up on how to make my EventSubscriber code run on every page load. In my src/EventSubscriber/RedirectAnonymousSubscriber.php file here's my code:

<?php

namespace Drupal\mymodule\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;


/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {
  private $redirectCode = 301;

  public function checkForRedirection(GetResponseEvent $event) {
    $is_authenticated = \Drupal::currentUser()->isAuthenticated();
    $route_name = \Drupal::routeMatch()->getRouteName();

    if (!$is_authenticated && $route_name !== 'user.login') {
      $response = new RedirectResponse('https://example.com', $this->redirectCode);
      $response->send();
      exit(0);
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }
}

And then my .services.yml file:

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\RedirectAnonymousSubscriber
    tags:
      - { name: event_subscriber }

The weird thing is when I run drush cr and pull up my local env, the first time I log in the redirection works, however, anytime I log in after the first time running drush cr the redirection does not work correctly. I even put a breakpoint on my if statement in my function and it doesn't get hit after the first successful redirection. Hope that makes sense. Thanks!

1