You are here

public function GraphQLLanguageContext::executeInLanguageContext in GraphQL 8.3

Executes a callable in a defined language context.

Parameters

callable $callable: The callable to be executed.

string $language: The langcode to be set.

Return value

mixed The callables result.

Throws

\Exception Any exception caught while executing the callable.

File

src/GraphQLLanguageContext.php, line 85

Class

GraphQLLanguageContext
Simple service that stores the current GraphQL language state.

Namespace

Drupal\graphql

Code

public function executeInLanguageContext(callable $callable, $language) {
  $this->languageStack
    ->push($this->currentLanguage);
  $this->currentLanguage = $language;
  $this->isActive = TRUE;
  $this->languageManager
    ->reset();

  // This is needed to be able to use the string translation with the
  // requested language.
  $this->translationManager
    ->setDefaultLangcode($language);

  // Override the configuration language so that config entities (like menus)
  // are loaded using the proper translation.
  $currentConfigLanguage = $this->languageManager
    ->getConfigOverrideLanguage();
  if ($currentConfigLanguage
    ->getId() !== $language) {
    $configLanguage = $this->languageManager
      ->getLanguage($language);
    $this->languageManager
      ->setConfigOverrideLanguage($configLanguage);
  }

  // Extract the result array.
  try {
    return call_user_func($callable);
  } catch (\Exception $exc) {
    throw $exc;
  } finally {

    // In any case, set the language context back to null.
    $this->currentLanguage = $this->languageStack
      ->pop();
    $this->isActive = FALSE;
    $this->languageManager
      ->reset();

    // Restore the languages for the translation and language managers.
    $defaultLangcode = !empty($this->currentLanguage) ? $this->currentLanguage : $this->languageManager
      ->getDefaultLanguage()
      ->getId();
    $this->translationManager
      ->setDefaultLangcode($defaultLangcode);
    $this->languageManager
      ->setConfigOverrideLanguage($currentConfigLanguage);
  }
}