rabbit_hole_links-1.0.2/src/RabbitHoleLinksLinkGenerator.php
src/RabbitHoleLinksLinkGenerator.php
<?php declare(strict_types=1); namespace Drupal\rabbit_hole_links; use Drupal\Core\Entity\ContentEntityInterface; use Drupal\Core\Extension\ModuleHandlerInterface; use Drupal\Core\GeneratedLink; use Drupal\Core\Link; use Drupal\Core\Url; use Drupal\Core\Utility\LinkGeneratorInterface; use Drupal\rabbit_hole\BehaviorInvokerInterface; /** * Decorates the link generator. */ class RabbitHoleLinksLinkGenerator implements RabbitHoleLinksLinkGeneratorInterface { /** * Constructs a RabbitHoleLinksLinkGenerator object. * * @param \Drupal\Core\Utility\LinkGeneratorInterface $inner * The current site context. * @param \Drupal\rabbit_hole\BehaviorInvokerInterface $behaviorInvoker * Rabbit hole behavior invoker. * @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler * The module handler. */ public function __construct( protected readonly LinkGeneratorInterface $inner, protected readonly BehaviorInvokerInterface $behaviorInvoker, protected readonly ModuleHandlerInterface $moduleHandler ) {} /** * {@inheritdoc} */ public function generate($text, Url $url): GeneratedLink { $url = $this->alterUrl($url); return $this->inner->generate($text, $url); } /** * Alters the url object. * * @param \Drupal\Core\Url $url * The url. * * @return \Drupal\Core\Url * The altered url. */ public function alterUrl(Url $url): Url { if (!$url->isExternal() && $url->isRouted()) { /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */ if (($entity = $url->getOption('entity')) && $entity instanceof ContentEntityInterface) { if ($entity->hasLinkTemplate('canonical') && $entity->toUrl('canonical') == $url && $rabbit_hole_behavior_plugin = $this->behaviorInvoker->getBehaviorPlugin($entity)) { $configuration = $rabbit_hole_behavior_plugin->getConfiguration(); if (isset($configuration['action'])) { switch ($configuration['action']) { case 'page_not_found': case 'access_denied': $url = Url::fromRoute('<nolink>'); break; case 'page_redirect': // Don't break if empty: $url = $configuration['redirect']; if (!$url) { break; } $url_lower = strtolower($url); // Check if url is external: if (str_starts_with($url_lower, 'http') || str_starts_with($url_lower, '//')) { return Url::fromUri($url); } return Url::fromUserInput($url); default: break; } } // Allows altering the url for other rabbit_hole_behavior plugins. $this->moduleHandler->alter('rabbit_hole_links', $url, $rabbit_hole_behavior_plugin); } } } return $url; } /** * {@inheritdoc} */ public function generateFromLink(Link $link): GeneratedLink { return $this->inner->generateFromLink($link); } }