Skip to content

Instantly share code, notes, and snippets.

@BirkAndMe
Created August 28, 2023 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BirkAndMe/7422a58d33f1e7c199774c5cc54873e3 to your computer and use it in GitHub Desktop.
Save BirkAndMe/7422a58d33f1e7c199774c5cc54873e3 to your computer and use it in GitHub Desktop.
Drupal 8 HTTP redirection from anywhere
services:
drupalgoto.event_subscriber:
class: Drupal\drupalgoto\EventSubscriber\EventSubscriber
tags:
- { name: event_subscriber }
<?php
namespace Drupal\drupalgoto\EventSubscriber;
use Drupal\drupalgoto\Exception\OverrideResponseException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Event subscriber.
*/
class EventSubscriber implements EventSubscriberInterface {
/**
* Exception event.
*/
public function onKernelException(ExceptionEvent $event) {
$throwable = $event->getThrowable();
if ($throwable instanceof OverrideResponseException) {
$event->setResponse($throwable->getResponse());
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
KernelEvents::EXCEPTION => ['onKernelException'],
];
}
}
<?php
namespace Drupal\drupalgoto\EventSubscriber;
use Symfony\Component\HttpFoundation\Response;
/**
* Override response exception.
*/
class OverrideResponseException extends \RuntimeException {
/**
*
*/
protected $response;
/**
* Construct instance.
*/
public function __construct(Response $response = null, ?string $message = '', \Throwable $previous = null, int $code = 0) {
$this->response = $response;
parent::__construct($message, $code, $previous);
}
/**
* Get response.
*/
public function getResponse() {
return $this->response;
}
}
<?php
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\drupalgoto\Exception\OverrideResponseException;
// Somewhere you want to make a redirection
$redirect = new TrustedRedirectResponse('https://...');
throw new OverrideResponseException($redirect);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment