5e1756918ef2890846cec8f4f1a03c4e650ad1fd
[yaffs-website] / web / core / modules / user / src / ContextProvider / CurrentUserContext.php
1 <?php
2
3 namespace Drupal\user\ContextProvider;
4
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;
11
12 /**
13  * Sets the current user as a context.
14  */
15 class CurrentUserContext implements ContextProviderInterface {
16
17   use StringTranslationTrait;
18
19   /**
20    * The current user.
21    *
22    * @var \Drupal\Core\Session\AccountInterface
23    */
24   protected $account;
25
26   /**
27    * The user storage.
28    *
29    * @var \Drupal\user\UserStorageInterface
30    */
31   protected $userStorage;
32
33   /**
34    * Constructs a new CurrentUserContext.
35    *
36    * @param \Drupal\Core\Session\AccountInterface $account
37    *   The current user.
38    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
39    *   The entity manager.
40    */
41   public function __construct(AccountInterface $account, EntityManagerInterface $entity_manager) {
42     $this->account = $account;
43     $this->userStorage = $entity_manager->getStorage('user');
44   }
45
46   /**
47    * {@inheritdoc}
48    */
49   public function getRuntimeContexts(array $unqualified_context_ids) {
50     $current_user = $this->userStorage->load($this->account->id());
51
52     if ($current_user) {
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;
56     }
57
58     $context = EntityContext::fromEntity($current_user, $this->t('Current user'));
59     $cacheability = new CacheableMetadata();
60     $cacheability->setCacheContexts(['user']);
61     $context->addCacheableDependency($cacheability);
62
63     $result = [
64       'current_user' => $context,
65     ];
66
67     return $result;
68   }
69
70   /**
71    * {@inheritdoc}
72    */
73   public function getAvailableContexts() {
74     return $this->getRuntimeContexts([]);
75   }
76
77 }