Updated to Drupal 8.5. Core Media not yet in use.
[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\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;
12
13 /**
14  * Sets the current user as a context.
15  */
16 class CurrentUserContext implements ContextProviderInterface {
17
18   use StringTranslationTrait;
19
20   /**
21    * The current user.
22    *
23    * @var \Drupal\Core\Session\AccountInterface
24    */
25   protected $account;
26
27   /**
28    * The user storage.
29    *
30    * @var \Drupal\user\UserStorageInterface
31    */
32   protected $userStorage;
33
34   /**
35    * Constructs a new CurrentUserContext.
36    *
37    * @param \Drupal\Core\Session\AccountInterface $account
38    *   The current user.
39    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
40    *   The entity manager.
41    */
42   public function __construct(AccountInterface $account, EntityManagerInterface $entity_manager) {
43     $this->account = $account;
44     $this->userStorage = $entity_manager->getStorage('user');
45   }
46
47   /**
48    * {@inheritdoc}
49    */
50   public function getRuntimeContexts(array $unqualified_context_ids) {
51     $current_user = $this->userStorage->load($this->account->id());
52
53     if ($current_user) {
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;
57     }
58
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);
63
64     $result = [
65       'current_user' => $context,
66     ];
67
68     return $result;
69   }
70
71   /**
72    * {@inheritdoc}
73    */
74   public function getAvailableContexts() {
75     return $this->getRuntimeContexts([]);
76   }
77
78 }