You are here

public function TokenReplacer::replaceContext in Menu Token 8

Same name and namespace in other branches
  1. 9.1.x src/Service/TokenReplacer.php \Drupal\menu_token\Service\TokenReplacer::replaceContext()

Replace token string with the value from context.

Parameters

string $token: Token to be replaced.

string $key: Key in token.

\Drupal\Core\Render\BubbleableMetadata $b: Bubable metadata for cache context.

Return value

array|string Returns replaced token.

File

src/Service/TokenReplacer.php, line 83

Class

TokenReplacer
TokenReplacer class.

Namespace

Drupal\menu_token\Service

Code

public function replaceContext($token, $key, BubbleableMetadata $b) {
  $token_type = $this
    ->getTokenType($token);
  $entity_type = $this->tokenEntityMapper
    ->getEntityTypeForTokenType($token_type);
  $b
    ->addCacheContexts([
    "url",
  ]);
  $b
    ->addCacheContexts([
    "user",
  ]);

  // If there is no entity type we are in trouble..
  if ($entity_type === FALSE) {
    return "";
  }
  $contexts_def = $this->contextRepository
    ->getAvailableContexts();
  $real_context = $this->contextRepository
    ->getRuntimeContexts(array_keys($contexts_def));
  foreach ($real_context as $key_i => $real_ci) {
    if (!$real_ci
      ->hasContextValue()) {
      continue;
    }
    $context_data_definition_type = $real_ci
      ->getContextData()
      ->getPluginDefinition();
    $value = $real_ci
      ->getContextData()
      ->getValue();

    // Service contextRepository does not return value as expected
    // on anonymous users.
    if ($entity_type == "user" && method_exists($value, "isAnonymous") && $value
      ->isAnonymous()) {

      // $value = User::load(\Drupal::currentUser()->id());.
      // Drupal screw me... User will always ask why
      // there are nothing shown for anonymous user..
      // Let them have string Anonymous and they will be happy and quiet.
      return [
        $token => "Anonymous",
      ];
    }
    if (empty($value)) {
      switch ($entity_type) {
        case "user":
          $value = User::load(\Drupal::currentUser()
            ->id());
          break;
        default:
          break;
      }
    }
    if ($context_data_definition_type["id"] == "entity" && method_exists($value, "getEntityTypeId") && $value
      ->getEntityTypeId() == $entity_type) {
      if (!empty($value)) {
        $r_var = $value;
        if (is_array($r_var)) {
          $r_var = array_pop($r_var);
        }
        $replacement = $this->tokenService
          ->generate($token_type, [
          $key => $token,
        ], [
          $token_type => $r_var,
        ], [], $b);
        return $replacement;
      }
    }
  }
  return "";
}