CurrentDomainContext.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace Drupal\domain\ContextProvider;
  3. use Drupal\domain\DomainNegotiatorInterface;
  4. use Drupal\Core\Cache\CacheableMetadata;
  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. * Provides a context handler for the block system.
  11. */
  12. class CurrentDomainContext implements ContextProviderInterface {
  13. use StringTranslationTrait;
  14. /**
  15. * The Domain negotiator.
  16. *
  17. * @var \Drupal\domain\DomainNegotiatorInterface
  18. */
  19. protected $negotiator;
  20. /**
  21. * Constructs a CurrentDomainContext object.
  22. *
  23. * @param \Drupal\domain\DomainNegotiatorInterface $negotiator
  24. * The domain negotiator.
  25. */
  26. public function __construct(DomainNegotiatorInterface $negotiator) {
  27. $this->negotiator = $negotiator;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function getRuntimeContexts(array $unqualified_context_ids) {
  33. // Load the current domain.
  34. $current_domain = $this->negotiator->getActiveDomain();
  35. // Set the context.
  36. $context = new Context(new ContextDefinition('entity:domain', $this->t('Active domain')), $current_domain);
  37. // Allow caching.
  38. $cacheability = new CacheableMetadata();
  39. $cacheability->setCacheContexts(['url.site']);
  40. $context->addCacheableDependency($cacheability);
  41. // Prepare the result.
  42. $result = [
  43. 'entity:domain' => $context,
  44. ];
  45. return $result;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function getAvailableContexts() {
  51. $context = new Context(new ContextDefinition('entity:domain', $this->t('Active domain')));
  52. return ['entity:domain' => $context];
  53. }
  54. }