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\Context;
|
Chris@0
|
8 use Drupal\Core\Plugin\Context\ContextDefinition;
|
Chris@0
|
9 use Drupal\Core\Plugin\Context\ContextProviderInterface;
|
Chris@0
|
10 use Drupal\Core\Session\AccountInterface;
|
Chris@0
|
11 use Drupal\Core\StringTranslation\StringTranslationTrait;
|
Chris@0
|
12
|
Chris@0
|
13 /**
|
Chris@0
|
14 * Sets the current user as a context.
|
Chris@0
|
15 */
|
Chris@0
|
16 class CurrentUserContext implements ContextProviderInterface {
|
Chris@0
|
17
|
Chris@0
|
18 use StringTranslationTrait;
|
Chris@0
|
19
|
Chris@0
|
20 /**
|
Chris@0
|
21 * The current user.
|
Chris@0
|
22 *
|
Chris@0
|
23 * @var \Drupal\Core\Session\AccountInterface
|
Chris@0
|
24 */
|
Chris@0
|
25 protected $account;
|
Chris@0
|
26
|
Chris@0
|
27 /**
|
Chris@0
|
28 * The user storage.
|
Chris@0
|
29 *
|
Chris@0
|
30 * @var \Drupal\user\UserStorageInterface
|
Chris@0
|
31 */
|
Chris@0
|
32 protected $userStorage;
|
Chris@0
|
33
|
Chris@0
|
34 /**
|
Chris@0
|
35 * Constructs a new CurrentUserContext.
|
Chris@0
|
36 *
|
Chris@0
|
37 * @param \Drupal\Core\Session\AccountInterface $account
|
Chris@0
|
38 * The current user.
|
Chris@0
|
39 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
|
Chris@0
|
40 * The entity manager.
|
Chris@0
|
41 */
|
Chris@0
|
42 public function __construct(AccountInterface $account, EntityManagerInterface $entity_manager) {
|
Chris@0
|
43 $this->account = $account;
|
Chris@0
|
44 $this->userStorage = $entity_manager->getStorage('user');
|
Chris@0
|
45 }
|
Chris@0
|
46
|
Chris@0
|
47 /**
|
Chris@0
|
48 * {@inheritdoc}
|
Chris@0
|
49 */
|
Chris@0
|
50 public function getRuntimeContexts(array $unqualified_context_ids) {
|
Chris@0
|
51 $current_user = $this->userStorage->load($this->account->id());
|
Chris@0
|
52
|
Chris@0
|
53 $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user);
|
Chris@0
|
54 $cacheability = new CacheableMetadata();
|
Chris@0
|
55 $cacheability->setCacheContexts(['user']);
|
Chris@0
|
56 $context->addCacheableDependency($cacheability);
|
Chris@0
|
57
|
Chris@0
|
58 $result = [
|
Chris@0
|
59 'current_user' => $context,
|
Chris@0
|
60 ];
|
Chris@0
|
61
|
Chris@0
|
62 return $result;
|
Chris@0
|
63 }
|
Chris@0
|
64
|
Chris@0
|
65 /**
|
Chris@0
|
66 * {@inheritdoc}
|
Chris@0
|
67 */
|
Chris@0
|
68 public function getAvailableContexts() {
|
Chris@0
|
69 return $this->getRuntimeContexts([]);
|
Chris@0
|
70 }
|
Chris@0
|
71
|
Chris@0
|
72 }
|