<?php

/**
 * @file
 * Module implementation file.
 */

/**
 * Implements hook_preprocess_menu_local_action().
 */
function nodehive_area_fragment_preprocess_menu_local_action(&$variables) {
  $allowed_routes = [
    'entity.nodehive_area.space_collection',
    'entity.fragment.space_collection',
  ];

  if (!in_array(\Drupal::routeMatch()->getRouteName(), $allowed_routes)) {
    return;
  }

  /** @var \Drupal\nodehive_core\SpaceInterface|null $space */
  $space_id = \Drupal::routeMatch()->getParameter('nodehive_space');
  if (!$space_id) {
    return;
  }

  $space = \Drupal::entityTypeManager()
    ->getStorage('nodehive_space')
    ->load($space_id);

  $query = $variables['link']['#url']->getOption('query');
  $query['nodehive_space'] = $space->id();

  $variables['link']['#url']->setOption('query', $query);
}
