3 namespace Drupal\Core\Language\ContextProvider;
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Language\LanguageManagerInterface;
7 use Drupal\Core\Plugin\Context\Context;
8 use Drupal\Core\Plugin\Context\ContextDefinition;
9 use Drupal\Core\Plugin\Context\ContextProviderInterface;
10 use Drupal\Core\StringTranslation\StringTranslationTrait;
13 * Sets the current language as a context.
15 class CurrentLanguageContext implements ContextProviderInterface {
17 use StringTranslationTrait;
20 * The language manager.
22 * @var \Drupal\Core\Language\LanguageManagerInterface
24 protected $languageManager;
27 * Constructs a new CurrentLanguageContext.
29 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
30 * The language manager.
32 public function __construct(LanguageManagerInterface $language_manager) {
33 $this->languageManager = $language_manager;
39 public function getRuntimeContexts(array $unqualified_context_ids) {
40 // Add a context for each language type.
41 $language_types = $this->languageManager->getLanguageTypes();
42 $info = $this->languageManager->getDefinedLanguageTypesInfo();
44 if ($unqualified_context_ids) {
45 foreach ($unqualified_context_ids as $unqualified_context_id) {
46 if (array_search($unqualified_context_id, $language_types) === FALSE) {
47 unset($language_types[$unqualified_context_id]);
53 foreach ($language_types as $type_key) {
54 if (isset($info[$type_key]['name'])) {
55 $context = new Context(new ContextDefinition('language', $info[$type_key]['name']), $this->languageManager->getCurrentLanguage($type_key));
57 $cacheability = new CacheableMetadata();
58 $cacheability->setCacheContexts(['languages:' . $type_key]);
59 $context->addCacheableDependency($cacheability);
61 $result[$type_key] = $context;
71 public function getAvailableContexts() {
72 return $this->getRuntimeContexts([]);