22
33namespace Drupal \graphql ;
44
5+ use Drupal \Core \Language \LanguageDefault ;
56use Drupal \Core \Language \LanguageManagerInterface ;
7+ use Drupal \Core \StringTranslation \TranslationManager ;
68
79/**
810 * Simple service that stores the current GraphQL language state.
@@ -35,14 +37,22 @@ class GraphQLLanguageContext {
3537 */
3638 protected $ languageManager ;
3739
40+ /**
41+ * The string translation service
42+ *
43+ * @var \Drupal\Core\StringTranslation\TranslationManager
44+ */
45+ protected $ translationManager ;
46+
3847 /**
3948 * GraphQLLanguageContext constructor.
4049 *
4150 * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
4251 * The language manager service.
4352 */
44- public function __construct (LanguageManagerInterface $ languageManager ) {
53+ public function __construct (LanguageManagerInterface $ languageManager, TranslationManager $ translationManager ) {
4554 $ this ->languageManager = $ languageManager ;
55+ $ this ->translationManager = $ translationManager ;
4656 $ this ->languageStack = new \SplStack ();
4757 }
4858
@@ -77,6 +87,16 @@ public function executeInLanguageContext(callable $callable, $language) {
7787 $ this ->currentLanguage = $ language ;
7888 $ this ->isActive = TRUE ;
7989 $ this ->languageManager ->reset ();
90+ // This is needed to be able to use the string translation with the
91+ // requested language.
92+ $ this ->translationManager ->setDefaultLangcode ($ language );
93+ // Override the configuration language so that config entities (like menus)
94+ // are loaded using the proper translation.
95+ $ currentConfigLanguage = $ this ->languageManager ->getConfigOverrideLanguage ();
96+ if ($ currentConfigLanguage ->getId () !== $ language ) {
97+ $ configLanguage = $ this ->languageManager ->getLanguage ($ language );
98+ $ this ->languageManager ->setConfigOverrideLanguage ($ configLanguage );
99+ }
80100 // Extract the result array.
81101 try {
82102 return call_user_func ($ callable );
@@ -89,6 +109,12 @@ public function executeInLanguageContext(callable $callable, $language) {
89109 $ this ->currentLanguage = $ this ->languageStack ->pop ();
90110 $ this ->isActive = FALSE ;
91111 $ this ->languageManager ->reset ();
112+ // Restore the languages for the translation and language managers.
113+ $ defaultLangcode = !empty ($ this ->currentLanguage )
114+ ? $ this ->currentLanguage
115+ : $ this ->languageManager ->getDefaultLanguage ()->getId ();
116+ $ this ->translationManager ->setDefaultLangcode ($ defaultLangcode );
117+ $ this ->languageManager ->setConfigOverrideLanguage ($ currentConfigLanguage );
92118 }
93119 }
94120
0 commit comments