Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 namespace Drupal\user\ContextProvider;
|
Chris@0
|
4
|
Chris@0
|
5 use Drupal\Core\Cache\CacheableMetadata;
|
Chris@0
|
6 use Drupal\Core\Entity\EntityManagerInterface;
|
Chris@0
|
7 use Drupal\Core\Plugin\Context\ContextProviderInterface;
|
Chris@4
|
8 use Drupal\Core\Plugin\Context\EntityContext;
|
Chris@0
|
9 use Drupal\Core\Session\AccountInterface;
|
Chris@0
|
10 use Drupal\Core\StringTranslation\StringTranslationTrait;
|
Chris@0
|
11
|
Chris@0
|
12 /**
|
Chris@0
|
13 * Sets the current user as a context.
|
Chris@0
|
14 */
|
Chris@0
|
15 class CurrentUserContext implements ContextProviderInterface {
|
Chris@0
|
16
|
Chris@0
|
17 use StringTranslationTrait;
|
Chris@0
|
18
|
Chris@0
|
19 /**
|
Chris@0
|
20 * The current user.
|
Chris@0
|
21 *
|
Chris@0
|
22 * @var \Drupal\Core\Session\AccountInterface
|
Chris@0
|
23 */
|
Chris@0
|
24 protected $account;
|
Chris@0
|
25
|
Chris@0
|
26 /**
|
Chris@0
|
27 * The user storage.
|
Chris@0
|
28 *
|
Chris@0
|
29 * @var \Drupal\user\UserStorageInterface
|
Chris@0
|
30 */
|
Chris@0
|
31 protected $userStorage;
|
Chris@0
|
32
|
Chris@0
|
33 /**
|
Chris@0
|
34 * Constructs a new CurrentUserContext.
|
Chris@0
|
35 *
|
Chris@0
|
36 * @param \Drupal\Core\Session\AccountInterface $account
|
Chris@0
|
37 * The current user.
|
Chris@0
|
38 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
|
Chris@0
|
39 * The entity manager.
|
Chris@0
|
40 */
|
Chris@0
|
41 public function __construct(AccountInterface $account, EntityManagerInterface $entity_manager) {
|
Chris@0
|
42 $this->account = $account;
|
Chris@0
|
43 $this->userStorage = $entity_manager->getStorage('user');
|
Chris@0
|
44 }
|
Chris@0
|
45
|
Chris@0
|
46 /**
|
Chris@0
|
47 * {@inheritdoc}
|
Chris@0
|
48 */
|
Chris@0
|
49 public function getRuntimeContexts(array $unqualified_context_ids) {
|
Chris@0
|
50 $current_user = $this->userStorage->load($this->account->id());
|
Chris@0
|
51
|
Chris@0
|
52 if ($current_user) {
|
Chris@0
|
53 // @todo Do not validate protected fields to avoid bug in TypedData,
|
Chris@0
|
54 // remove this in https://www.drupal.org/project/drupal/issues/2934192.
|
Chris@0
|
55 $current_user->_skipProtectedUserFieldConstraint = TRUE;
|
Chris@0
|
56 }
|
Chris@0
|
57
|
Chris@4
|
58 $context = EntityContext::fromEntity($current_user, $this->t('Current user'));
|
Chris@0
|
59 $cacheability = new CacheableMetadata();
|
Chris@0
|
60 $cacheability->setCacheContexts(['user']);
|
Chris@0
|
61 $context->addCacheableDependency($cacheability);
|
Chris@0
|
62
|
Chris@0
|
63 $result = [
|
Chris@0
|
64 'current_user' => $context,
|
Chris@0
|
65 ];
|
Chris@0
|
66
|
Chris@0
|
67 return $result;
|
Chris@0
|
68 }
|
Chris@0
|
69
|
Chris@0
|
70 /**
|
Chris@0
|
71 * {@inheritdoc}
|
Chris@0
|
72 */
|
Chris@0
|
73 public function getAvailableContexts() {
|
Chris@0
|
74 return $this->getRuntimeContexts([]);
|
Chris@0
|
75 }
|
Chris@0
|
76
|
Chris@0
|
77 }
|