Skip to content

Instantly share code, notes, and snippets.

@hudri
Last active April 19, 2018 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hudri/0913a2086ed0c0d70c9828724c8728c2 to your computer and use it in GitHub Desktop.
Save hudri/0913a2086ed0c0d70c9828724c8728c2 to your computer and use it in GitHub Desktop.
Modify _all_ Drupal links
<?php
namespace Drupal\wt_base;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Render\BubbleableMetadata;
/**
* Class DefaultService.
*/
class LinkModifierService implements OutboundPathProcessorInterface {
/**
* Symfony\Component\HttpFoundation\RequestStack definition.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* Constructs a new DefaultService object.
*/
public function __construct(RequestStack $request_stack) {
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
if (empty($request)) {
$request = $this->requestStack->getCurrentRequest();
}
// On every page of type "product" add the product id as query parameter to every link on that page
// no matter if that link is in a menu, a block or in a CKeditor text field of the node.
// It does only modify interal though, but not links to external homepages.
$node = $request->attributes->get('node');
if ($node && $node->bundle() === 'product') {
$options['query'][] = [$node->bundle() => $node->id()];
}
return $path;
}
}
services:
wt_base.link_modifier_service:
class: Drupal\wt_base\LinkModifierService
tags:
- { name: path_processor_outbound, priority: 3000 }
arguments: ['@request_stack']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment