Skip to content

Instantly share code, notes, and snippets.

@heddn
Created January 22, 2018 20:12
Show Gist options
  • Save heddn/4aa760e0516a6212d9531a50a82a0683 to your computer and use it in GitHub Desktop.
Save heddn/4aa760e0516a6212d9531a50a82a0683 to your computer and use it in GitHub Desktop.
<?php
namespace Drupal\example\EventSubscriber;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class UserPageRedirect.
*/
class UserPageRedirect implements EventSubscriberInterface {
/**
* Drupal\Core\Routing\CurrentRouteMatch definition.
*
* @var \Drupal\Core\Routing\CurrentRouteMatch
*/
protected $currentRouteMatch;
/**
* Drupal\Core\Session\AccountProxyInterface definition.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* Constructs a new UserPageRedirect object.
*
* @param \Drupal\Core\Routing\CurrentRouteMatch $current_route_match
* The current route match.
* @param \Drupal\Core\Session\AccountProxyInterface $current_user
* The current user.
*/
public function __construct(CurrentRouteMatch $current_route_match, AccountProxyInterface $current_user) {
$this->currentRouteMatch = $current_route_match;
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE] = ['onPageView'];
return $events;
}
/**
* Called whenever the kernel.response event is dispatched.
*
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* The response event.
*/
public function onPageView(FilterResponseEvent $event) {
// Only concern ourselves with a few routes.
$redirected_routes = [
'entity.user.canonical',
];
$current_route = $this->currentRouteMatch->getRouteName();
if (!in_array($current_route, $redirected_routes)) {
return;
}
// user.page is only viewable by the current user.
if ($url = Url::fromRoute('entity.user.edit_form', ['user' => $uid])) {
if ($url->access()) {
$response = new RedirectResponse($url->toString());
$event->setResponse($response);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment