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());
54 // @todo Do not validate protected fields to avoid bug in TypedData,
55 // remove this in https://www.drupal.org/project/drupal/issues/2934192.
56 $current_user->_skipProtectedUserFieldConstraint = TRUE;
59 $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user);
60 $cacheability = new CacheableMetadata();
61 $cacheability->setCacheContexts(['user']);
62 $context->addCacheableDependency($cacheability);
65 'current_user' => $context,
74 public function getAvailableContexts() {
75 return $this->getRuntimeContexts([]);