Created
November 9, 2017 09:06
-
-
Save flocondetoile/e5d880ad2c032030166de682afef1658 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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