<?php

namespace Drupal\reader\EventSubscriber;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Redirects users when access is denied.
 *
 * Anonymous users are taken to the login page when attempting to access the
 * user profile pages. Authenticated users are redirected from the login form to
 * their profile page and from the user registration form to their profile edit
 * form.
 */
class ReaderAccessDeniedSubscriber implements EventSubscriberInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $account;

  /**
   * Constructs a new redirect subscriber.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   */
  public function __construct(AccountInterface $account) {
    $this->account = $account;
  }

  /**
   * Redirects users when access is denied.
   *
   * @param $event
   *   The event to process.
   */
  public function onException($event) {
    $exception = method_exists($event, 'getThrowable') ? $event->getThrowable() : $event->getException();
    if ($exception instanceof AccessDeniedHttpException) {
      $route_name = RouteMatch::createFromRequest($event->getRequest())->getRouteName();
      $redirect_url = NULL;

      if ($this->account->isAnonymous()) {
        if (in_array($route_name, ['reader.home', 'reader.add', 'reader.timeline'])) {
          $redirect_url = Url::fromRoute('reader.login', [], ['absolute' => TRUE]);
        }
      }

      if ($redirect_url) {
        $event->setResponse(new RedirectResponse($redirect_url->toString()));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    // Use a higher priority than
    // \Drupal\user\EventSubscriber\AccessDeniedSubscriber, because we want to
    // check first on redirecting.
    $events[KernelEvents::EXCEPTION][] = ['onException', 100];
    return $events;
  }

}
