3 namespace Drupal\user\ContextProvider;
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Entity\EntityManagerInterface;
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\Session\AccountInterface;
11 use Drupal\Core\StringTranslation\StringTranslationTrait;
14 * Sets the current user as a context.
16 class CurrentUserContext implements ContextProviderInterface {
18 use StringTranslationTrait;
23 * @var \Drupal\Core\Session\AccountInterface
30 * @var \Drupal\user\UserStorageInterface
32 protected $userStorage;
35 * Constructs a new CurrentUserContext.
37 * @param \Drupal\Core\Session\AccountInterface $account
39 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
42 public function __construct(AccountInterface $account, EntityManagerInterface $entity_manager) {
43 $this->account = $account;
44 $this->userStorage = $entity_manager->getStorage('user');
50 public function getRuntimeContexts(array $unqualified_context_ids) {
51 $current_user = $this->userStorage->load($this->account->id());
53 $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user);
54 $cacheability = new CacheableMetadata();
55 $cacheability->setCacheContexts(['user']);
56 $context->addCacheableDependency($cacheability);
59 'current_user' => $context,
68 public function getAvailableContexts() {
69 return $this->getRuntimeContexts([]);