Search code examples
phpurldrupaldrupal-8alter

Drupal 8 Url Alter with processOutbound and preg_replace


I am working on a Drupal website where I need to change all the URL containing "member" to "follower".

Ex:

  • www.site.com/member ====> www.site.com/follower
  • www.site.com/members ====> www.site.com/followers
  • www.site.com/members/1/info ====> www.site.com/followers/1/info
  • www.site.com/something/member ====> www.site.com/something/follower

etc.

I tried several stuff that did not work and then I found out about processOutbound that seems to be the right way to replace "member" by "follower" in all my URLs.

But it does not work neither. Could you guys please help me resolve this ?

Please find the code of my class below.

class SquarePathProcessor implements InboundPathProcessorInterface, OutboundPathProcessorInterface {

  public function processInbound($path, Request $request) {

    return $path;
  }

  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    return preg_replace('@^/member(.*)@', '/follower$1', $path);
  }
}

Solution

  • I did it !!! Here is the solution :

    class SquarePathProcessor implements InboundPathProcessorInterface, OutboundPathProcessorInterface {
    
      public function processInbound($path, Request $request) {
        if (strpos($path, '/follower') === 0) {
          $path = preg_replace('#^/follower#', '/member', $path);
        }
        return $path;
      }
    
      public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
        if (strpos($path, '/member') === 0) {
          $path = preg_replace('#^/member#', '/follower', $path);
        }
        return $path;
      }
    
    }
    

    Thank you all