Problem/Motivation

A comment permalink URL is like this:

https://example.com/comment/CID#comment-CID

The page at this URL contains the node and the comments. Because it contains the node, Drupal sees this as an internal redirect to the node route. So, functions like \Drupal::routeMatch() and \Drupal::request()->getRequestUri() return information about the node. The only way I have found to get the comment ID is to directly access $_SERVER['REQUEST_URI']. There should be an easier way.

Proposed resolution

Create a service that returns information about the actual request made by the browser without considering internal redirects.

Remaining tasks

Decide what to do. Implement.

User interface changes

None.

Introduced terminology

None.

API changes

New service.

Data model changes

None.

Release notes snippet

Comments

liam morland created an issue.

shank115’s picture

I had a quick look at this on 11.x with a comment permalink (/comment/1). I might be wrong here, but sharing in case it helps.

It looks like the original request is still available on the request stack. Both of these returned the comment in my test:
\Drupal::requestStack()->getMainRequest()
\Drupal::service('current_route_match')->getMasterRouteMatch()->getParameter('comment')

One thing I noticed, though: when I used that value during rendering (in a node view hook), it got cached and reused across pages. The value rendered for /comment/1 showed again on /comment/2. Adding the route or url cache context didn't seem to help, and /comment/2 still got the value from /comment/1. My guess is that these contexts read the node sub-request rather than the main request, but I am not fully sure. Setting max-age: 0 on the element avoided it, though that's probably not ideal.

So maybe only a service wouldn't be enough, and something like a cache context based on the main request could also be needed? Just a thought. There may well be a better existing approach I am not aware of.