3 namespace Drupal\user\ContextProvider;
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Entity\EntityManagerInterface;
7 use Drupal\Core\Plugin\Context\ContextProviderInterface;
8 use Drupal\Core\Plugin\Context\EntityContext;
9 use Drupal\Core\Session\AccountInterface;
10 use Drupal\Core\StringTranslation\StringTranslationTrait;
13 * Sets the current user as a context.
15 class CurrentUserContext implements ContextProviderInterface {
17 use StringTranslationTrait;
22 * @var \Drupal\Core\Session\AccountInterface
29 * @var \Drupal\user\UserStorageInterface
31 protected $userStorage;
34 * Constructs a new CurrentUserContext.
36 * @param \Drupal\Core\Session\AccountInterface $account
38 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
41 public function __construct(AccountInterface $account, EntityManagerInterface $entity_manager) {
42 $this->account = $account;
43 $this->userStorage = $entity_manager->getStorage('user');
49 public function getRuntimeContexts(array $unqualified_context_ids) {
50 $current_user = $this->userStorage->load($this->account->id());
53 // @todo Do not validate protected fields to avoid bug in TypedData,
54 // remove this in https://www.drupal.org/project/drupal/issues/2934192.
55 $current_user->_skipProtectedUserFieldConstraint = TRUE;
58 $context = EntityContext::fromEntity($current_user, $this->t('Current user'));
59 $cacheability = new CacheableMetadata();
60 $cacheability->setCacheContexts(['user']);
61 $context->addCacheableDependency($cacheability);
64 'current_user' => $context,
73 public function getAvailableContexts() {
74 return $this->getRuntimeContexts([]);