3

I'm doing some central static variable setup for the request and was hoping to use KernelEvents::REQUEST to run first and set the variables.

However, I've found that while the documentation states:

The REQUEST event occurs at the very beginning of request dispatching.

hook_node_access actually runs before the KernelEvents::REQUEST event handler:

  /**
   * The subscribed events.
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[KernelEvents::REQUEST][] = ['onKernelRequest', 1];
    return $events;
  }

then in the event listener:

  public function onKernelRequest(GetResponseEvent $event) {
    drupal_set_message(__FUNCTION__ . ': ' . microtime());
  }

and in hook_node_access

then in the event listener:

  public function mymodule_node_accesss(NodeInterface $node, $op, AccountInterface $account) {
    drupal_set_message(__FUNCTION__ . ': ' . microtime());
  }

Output:

mymodule_node_access: 0.76379200 1518995630
onKernelRequest: 0.77758400 1518995630

As we can see from microtime order, hook_node_access runs first. Anyway to make it run after the KernelEvents::REQUEST event handler? thanks.

4

OK, after a bit more digging, I found the solution.

The "weight" param for ['onKernelRequest', 1] is sort DESC, so the higher weight number will run first.

Adjusting the event listener with weight 1000 as follows means it runs before the hook_node_access invoking listener

  /**
   * The subscribed events.
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[KernelEvents::REQUEST][] = ['onKernelRequest', 1000];
    return $events;
  }
1
  • 3
    That is because weight is not a weight, it is a priority. The higher the value, the more important it is. This is coming directly from Symfony, that's why it is different to how weights in Drupal typically work. The access check happens as part of routing, which is priority 32, see \Symfony\Component\HttpKernel\EventListener\RouterListener::getSubscribedEvents. Instead of 1000, you might want to use something just slightly higher than that, because 1000 also runs before authentication (300) and other things that you might rely on – Berdir Feb 19 '18 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.