Skip to content

Instantly share code, notes, and snippets.

@flocondetoile
Created November 9, 2017 09:06
Show Gist options
  • Select an option

  • Save flocondetoile/e5d880ad2c032030166de682afef1658 to your computer and use it in GitHub Desktop.

Select an option

Save flocondetoile/e5d880ad2c032030166de682afef1658 to your computer and use it in GitHub Desktop.
<?php
namespace Drupal\MY_MODULE\EventSubscriber;
use Drupal\Core\Session\AccountInterface;
use Drupal\taxonomy\TermInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Routing\RouteMatch;
/**
* Class Subscriber.
*
* @package Drupal\MY_MODULE
*/
class TermAccessSubscriber implements EventSubscriberInterface {
/**
* the terms allowed to be accessed on their canonical page.
*
* @var array
*/
protected $allowed_terms;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Constructor.
*
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(AccountInterface $current_user) {
$this->currentUser = $current_user;
$this->allowed_terms = [
'service',
'expertise',
'territory',
'keyword',
'newsletter',
];
}
/**
* {@inheritdoc}
*/
static function getSubscribedEvents() {
$events[KernelEvents::REQUEST] = ['onRequestRedirect'];
return $events;
}
/**
* This method is called whenever the kernel.request event is
* dispatched.
*
* @param GetResponseEvent $event
*/
public function onRequestRedirect(GetResponseEvent $event) {
$request = $event->getRequest();
if ($this->currentUser->hasPermission('administer taxonomy')) {
return;
}
// If we've got an exception, nothing to do here.
if ($request->get('exception') != NULL) {
return;
}
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = $request->get('taxonomy_term');
$route_match = RouteMatch::createFromRequest($request);
$route_name = $route_match->getRouteName();
if ($term instanceof TermInterface && $route_name == 'entity.taxonomy_term.canonical') {
if (!in_array($term->bundle(), $this->allowed_terms)) {
throw new NotFoundHttpException();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment