CurrentLanguageContext.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Drupal\Core\Language\ContextProvider;
  3. use Drupal\Core\Cache\CacheableMetadata;
  4. use Drupal\Core\Language\LanguageManagerInterface;
  5. use Drupal\Core\Plugin\Context\Context;
  6. use Drupal\Core\Plugin\Context\ContextDefinition;
  7. use Drupal\Core\Plugin\Context\ContextProviderInterface;
  8. use Drupal\Core\StringTranslation\StringTranslationTrait;
  9. /**
  10. * Sets the current language as a context.
  11. */
  12. class CurrentLanguageContext implements ContextProviderInterface {
  13. use StringTranslationTrait;
  14. /**
  15. * The language manager.
  16. *
  17. * @var \Drupal\Core\Language\LanguageManagerInterface
  18. */
  19. protected $languageManager;
  20. /**
  21. * Constructs a new CurrentLanguageContext.
  22. *
  23. * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
  24. * The language manager.
  25. */
  26. public function __construct(LanguageManagerInterface $language_manager) {
  27. $this->languageManager = $language_manager;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function getRuntimeContexts(array $unqualified_context_ids) {
  33. // Add a context for each language type.
  34. $language_types = $this->languageManager->getLanguageTypes();
  35. $info = $this->languageManager->getDefinedLanguageTypesInfo();
  36. if ($unqualified_context_ids) {
  37. foreach ($unqualified_context_ids as $unqualified_context_id) {
  38. if (array_search($unqualified_context_id, $language_types) === FALSE) {
  39. unset($language_types[$unqualified_context_id]);
  40. }
  41. }
  42. }
  43. $result = [];
  44. foreach ($language_types as $type_key) {
  45. if (isset($info[$type_key]['name'])) {
  46. $context = new Context(new ContextDefinition('language', $info[$type_key]['name']), $this->languageManager->getCurrentLanguage($type_key));
  47. $cacheability = new CacheableMetadata();
  48. $cacheability->setCacheContexts(['languages:' . $type_key]);
  49. $context->addCacheableDependency($cacheability);
  50. $result[$type_key] = $context;
  51. }
  52. }
  53. return $result;
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function getAvailableContexts() {
  59. return $this->getRuntimeContexts([]);
  60. }
  61. }