1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
|
<?php
namespace Drupal\language;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\Language;
use Drupal\Core\Language\LanguageDefault;
use Drupal\Core\Language\LanguageManager;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\language\Config\LanguageConfigFactoryOverrideInterface;
use Drupal\language\Entity\ConfigurableLanguage;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Overrides default LanguageManager to provide configured languages.
*/
class ConfigurableLanguageManager extends LanguageManager implements ConfigurableLanguageManagerInterface {
/**
* The configuration storage service.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The language configuration override service.
*
* @var \Drupal\language\Config\LanguageConfigFactoryOverrideInterface
*/
protected $configFactoryOverride;
/**
* The request object.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* The language negotiator.
*
* @var \Drupal\language\LanguageNegotiatorInterface
*/
protected $negotiator;
/**
* Local cache for language type configuration data.
*
* @var array
*/
protected $languageTypes;
/**
* Local cache for language type information.
*
* @var array
*/
protected $languageTypesInfo;
/**
* An array of language objects keyed by language type.
*
* @var \Drupal\Core\Language\LanguageInterface[]
*/
protected $negotiatedLanguages;
/**
* An array of language negotiation method IDs keyed by language type.
*
* @var array
*/
protected $negotiatedMethods;
/**
* Whether or not the language manager has been initialized.
*
* @var bool
*/
protected $initialized = FALSE;
/**
* Whether language types are in the process of language initialization.
*
* @var bool[]
*/
protected $initializing = [];
/**
* {@inheritdoc}
*/
public static function rebuildServices() {
\Drupal::service('kernel')->invalidateContainer();
}
/**
* Constructs a new ConfigurableLanguageManager object.
*
* @param \Drupal\Core\Language\LanguageDefault $default_language
* The default language service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory service.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler service.
* @param \Drupal\language\Config\LanguageConfigFactoryOverrideInterface $config_override
* The language configuration override service.
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
* The request stack object.
*/
public function __construct(LanguageDefault $default_language, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, LanguageConfigFactoryOverrideInterface $config_override, RequestStack $request_stack) {
$this->defaultLanguage = $default_language;
$this->configFactory = $config_factory;
$this->moduleHandler = $module_handler;
$this->configFactoryOverride = $config_override;
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public function init() {
if (!$this->initialized) {
foreach ($this->getDefinedLanguageTypes() as $type) {
$this->getCurrentLanguage($type);
}
$this->initialized = TRUE;
}
}
/**
* {@inheritdoc}
*/
public function isMultilingual() {
return count($this->getLanguages(LanguageInterface::STATE_CONFIGURABLE)) > 1;
}
/**
* {@inheritdoc}
*/
public function getLanguageTypes() {
$this->loadLanguageTypesConfiguration();
return $this->languageTypes['configurable'];
}
/**
* {@inheritdoc}
*/
public function getDefinedLanguageTypes() {
$this->loadLanguageTypesConfiguration();
return $this->languageTypes['all'];
}
/**
* Retrieves language types from the configuration storage.
*
* @return array
* An array of language type names.
*/
protected function loadLanguageTypesConfiguration() {
if (!$this->languageTypes) {
$this->languageTypes = $this->configFactory->get('language.types')->get() ?: ['configurable' => [], 'all' => parent::getLanguageTypes()];
}
return $this->languageTypes;
}
/**
* {@inheritdoc}
*/
public function getDefinedLanguageTypesInfo() {
if (!isset($this->languageTypesInfo)) {
$defaults = parent::getDefinedLanguageTypesInfo();
$info = $this->moduleHandler->invokeAll('language_types_info');
$language_info = $info + $defaults;
// Let other modules alter the list of language types.
$this->moduleHandler->alter('language_types_info', $language_info);
$this->languageTypesInfo = $language_info;
}
return $this->languageTypesInfo;
}
/**
* {@inheritdoc}
*/
public function saveLanguageTypesConfiguration(array $values) {
$config = $this->configFactory->getEditable('language.types');
if (isset($values['configurable'])) {
$config->set('configurable', $values['configurable']);
}
if (isset($values['all'])) {
$config->set('all', $values['all']);
}
$config->save(TRUE);
}
/**
* {@inheritdoc}
*/
public function getCurrentLanguage($type = LanguageInterface::TYPE_INTERFACE) {
if (!isset($this->negotiatedLanguages[$type])) {
// Ensure we have a valid value for this language type.
$this->negotiatedLanguages[$type] = $this->getDefaultLanguage();
if ($this->negotiator && $this->isMultilingual()) {
if (!isset($this->initializing[$type])) {
$this->initializing[$type] = TRUE;
$negotiation = $this->negotiator->initializeType($type);
$this->negotiatedLanguages[$type] = reset($negotiation);
$this->negotiatedMethods[$type] = key($negotiation);
unset($this->initializing[$type]);
}
// If the current interface language needs to be retrieved during
// initialization we return the system language. This way string
// translation calls happening during initialization will return the
// original strings which can be translated by calling them again
// afterwards. This can happen for instance while parsing negotiation
// method definitions.
elseif ($type == LanguageInterface::TYPE_INTERFACE) {
return new Language(['id' => LanguageInterface::LANGCODE_SYSTEM]);
}
}
}
return $this->negotiatedLanguages[$type];
}
/**
* {@inheritdoc}
*/
public function reset($type = NULL) {
if (!isset($type)) {
$this->initialized = FALSE;
$this->negotiatedLanguages = [];
$this->negotiatedMethods = [];
$this->languageTypes = NULL;
$this->languageTypesInfo = NULL;
$this->languages = [];
if ($this->negotiator) {
$this->negotiator->reset();
}
}
elseif (isset($this->negotiatedLanguages[$type])) {
unset($this->negotiatedLanguages[$type]);
unset($this->negotiatedMethods[$type]);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function getNegotiator() {
return $this->negotiator;
}
/**
* {@inheritdoc}
*/
public function setNegotiator(LanguageNegotiatorInterface $negotiator) {
$this->negotiator = $negotiator;
$this->initialized = FALSE;
$this->negotiatedLanguages = [];
}
/**
* {@inheritdoc}
*/
public function getLanguages($flags = LanguageInterface::STATE_CONFIGURABLE) {
// If a config override is set, cache using that language's ID.
if ($override_language = $this->getConfigOverrideLanguage()) {
$static_cache_id = $override_language->getId();
}
else {
$static_cache_id = $this->getCurrentLanguage()->getId();
}
if (!isset($this->languages[$static_cache_id][$flags])) {
// Initialize the language list with the default language and default
// locked languages. These cannot be removed. This serves as a fallback
// list if this method is invoked while the language module is installed
// and the configuration entities for languages are not yet fully
// imported.
$default = $this->getDefaultLanguage();
$languages = [$default->getId() => $default];
$languages += $this->getDefaultLockedLanguages($default->getWeight());
// Load configurable languages on top of the defaults. Ideally this could
// use the entity API to load and instantiate ConfigurableLanguage
// objects. However the entity API depends on the language system, so that
// would result in infinite loops. We use the configuration system
// directly and instantiate runtime Language objects. When language
// entities are imported those cover the default and locked languages, so
// site-specific configuration will prevail over the fallback values.
// Having them in the array already ensures if this is invoked in the
// middle of importing language configuration entities, the defaults are
// always present.
$config_ids = $this->configFactory->listAll('language.entity.');
foreach ($this->configFactory->loadMultiple($config_ids) as $config) {
$data = $config->get();
$data['name'] = $data['label'];
$languages[$data['id']] = new Language($data);
}
Language::sort($languages);
// Filter the full list of languages based on the value of $flags.
$this->languages[$static_cache_id][$flags] = $this->filterLanguages($languages, $flags);
}
return $this->languages[$static_cache_id][$flags];
}
/**
* {@inheritdoc}
*/
public function getNativeLanguages() {
$languages = $this->getLanguages(LanguageInterface::STATE_CONFIGURABLE);
$natives = [];
$original_language = $this->getConfigOverrideLanguage();
foreach ($languages as $langcode => $language) {
$this->setConfigOverrideLanguage($language);
$natives[$langcode] = ConfigurableLanguage::load($langcode);
}
$this->setConfigOverrideLanguage($original_language);
Language::sort($natives);
return $natives;
}
/**
* {@inheritdoc}
*/
public function updateLockedLanguageWeights() {
// Get the weight of the last configurable language.
$configurable_languages = $this->getLanguages(LanguageInterface::STATE_CONFIGURABLE);
$max_weight = end($configurable_languages)->getWeight();
$locked_languages = $this->getLanguages(LanguageInterface::STATE_LOCKED);
// Update locked language weights to maintain the existing order, if
// necessary.
if (reset($locked_languages)->getWeight() <= $max_weight) {
foreach ($locked_languages as $language) {
// Update system languages weight.
$max_weight++;
ConfigurableLanguage::load($language->getId())
->setWeight($max_weight)
->save();
}
}
}
/**
* {@inheritdoc}
*/
public function getFallbackCandidates(array $context = []) {
if ($this->isMultilingual()) {
$candidates = [];
if (empty($context['operation']) || $context['operation'] != 'locale_lookup') {
// If the fallback context is not locale_lookup, initialize the
// candidates with languages ordered by weight and add
// LanguageInterface::LANGCODE_NOT_SPECIFIED at the end. Interface
// translation fallback should only be based on explicit configuration
// gathered via the alter hooks below.
$candidates = array_keys($this->getLanguages());
$candidates[] = LanguageInterface::LANGCODE_NOT_SPECIFIED;
$candidates = array_combine($candidates, $candidates);
// The first candidate should always be the desired language if
// specified.
if (!empty($context['langcode'])) {
$candidates = [$context['langcode'] => $context['langcode']] + $candidates;
}
}
// Let other modules hook in and add/change candidates.
$type = 'language_fallback_candidates';
$types = [];
if (!empty($context['operation'])) {
$types[] = $type . '_' . $context['operation'];
}
$types[] = $type;
$this->moduleHandler->alter($types, $candidates, $context);
}
else {
$candidates = parent::getFallbackCandidates($context);
}
return $candidates;
}
/**
* {@inheritdoc}
*/
public function getLanguageSwitchLinks($type, Url $url) {
if ($this->negotiator) {
foreach ($this->negotiator->getNegotiationMethods($type) as $method_id => $method) {
$reflector = new \ReflectionClass($method['class']);
if ($reflector->implementsInterface('\Drupal\language\LanguageSwitcherInterface')) {
$original_languages = $this->negotiatedLanguages;
$result = $this->negotiator->getNegotiationMethodInstance($method_id)->getLanguageSwitchLinks($this->requestStack->getCurrentRequest(), $type, $url);
if (!empty($result)) {
// Allow modules to provide translations for specific links.
$this->moduleHandler->alter('language_switch_links', $result, $type, $url);
$result = array_filter($result, function (array $link): bool {
$url = $link['url'] ?? NULL;
$language = $link['language'] ?? NULL;
if ($language instanceof LanguageInterface) {
$this->negotiatedLanguages[LanguageInterface::TYPE_CONTENT] = $language;
$this->negotiatedLanguages[LanguageInterface::TYPE_INTERFACE] = $language;
}
try {
return $url instanceof Url && $url->access();
}
catch (\Exception $e) {
return FALSE;
}
});
$this->negotiatedLanguages = $original_languages;
$links = (object) ['links' => $result, 'method_id' => $method_id];
break;
}
}
}
}
return $links ?? NULL;
}
/**
* Sets the configuration override language.
*
* @param \Drupal\Core\Language\LanguageInterface $language
* The language to override configuration with.
*
* @return $this
*/
public function setConfigOverrideLanguage(LanguageInterface $language = NULL) {
$this->configFactoryOverride->setLanguage($language);
return $this;
}
/**
* {@inheritdoc}
*/
public function getConfigOverrideLanguage() {
return $this->configFactoryOverride->getLanguage();
}
/**
* {@inheritdoc}
*/
public function getLanguageConfigOverride($langcode, $name) {
return $this->configFactoryOverride->getOverride($langcode, $name);
}
/**
* {@inheritdoc}
*/
public function getLanguageConfigOverrideStorage($langcode) {
return $this->configFactoryOverride->getStorage($langcode);
}
/**
* {@inheritdoc}
*/
public function getStandardLanguageListWithoutConfigured() {
$languages = $this->getLanguages();
$predefined = $this->getStandardLanguageList();
foreach ($predefined as $key => $value) {
if (isset($languages[$key])) {
unset($predefined[$key]);
continue;
}
$predefined[$key] = new TranslatableMarkup($value[0]);
}
natcasesort($predefined);
return $predefined;
}
/**
* {@inheritdoc}
*/
public function getNegotiatedLanguageMethod($type = LanguageInterface::TYPE_INTERFACE) {
if (isset($this->negotiatedLanguages[$type]) && isset($this->negotiatedMethods[$type])) {
return $this->negotiatedMethods[$type];
}
}
}
|