PreviewLinkRouteEventSubscriber.php in Preview Link 2.0.x
File
src/EventSubscriber/PreviewLinkRouteEventSubscriber.php
View source
<?php
declare (strict_types=1);
namespace Drupal\preview_link\EventSubscriber;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RedirectDestinationInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Url;
use Drupal\preview_link\Exception\PreviewLinkRerouteException;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class PreviewLinkRouteEventSubscriber implements EventSubscriberInterface {
use StringTranslationTrait;
protected $messenger;
protected $redirectDestination;
protected $currentUser;
protected $logger;
public function __construct(MessengerInterface $messenger, RedirectDestinationInterface $redirectDestination, TranslationInterface $stringTranslation, AccountInterface $currentUser, LoggerInterface $logger) {
$this->messenger = $messenger;
$this->redirectDestination = $redirectDestination;
$this->stringTranslation = $stringTranslation;
$this->currentUser = $currentUser;
$this->logger = $logger;
}
public function onException(GetResponseForExceptionEvent $event) : void {
$exception = $event
->getException();
if ($exception instanceof PreviewLinkRerouteException) {
$entity = $exception
->getEntity();
$token = $exception
->getPreviewLink()
->getToken();
$previewLinkUrl = Url::fromRoute('entity.' . $entity
->getEntityTypeId() . '.preview_link', [
$entity
->getEntityTypeId() => $entity
->id(),
'preview_token' => $token,
]);
$removeUrl = Url::fromRoute('preview_link.session_tokens.remove');
$destination = $this->redirectDestination
->get();
try {
$canonicalUrl = Url::fromUserInput($destination);
if ($canonicalUrl
->access($this->currentUser)) {
$removeUrl
->setOption('query', $this->redirectDestination
->getAsArray());
}
} catch (\InvalidArgumentException $e) {
}
$this->messenger
->addMessage($this
->t('You are viewing this page because a preview link granted you access. Click <a href="@remove_session_url">here</a> to remove token.', [
'@remove_session_url' => $removeUrl
->toString(),
]));
$this->logger
->debug('Redirecting to preview link of @entity', [
'@entity' => $entity
->label(),
]);
$response = (new TrustedRedirectResponse($previewLinkUrl
->toString(), TrustedRedirectResponse::HTTP_TEMPORARY_REDIRECT))
->addCacheableDependency($exception);
$event
->setResponse($response);
$event
->stopPropagation();
}
}
public static function getSubscribedEvents() : array {
$events[KernelEvents::EXCEPTION][] = [
'onException',
51,
];
return $events;
}
}