summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/user/src/ContextProvider/CurrentUserContext.php
blob: f1f69ad1480c1d70e07d2a00861a4ed5f0e26b40 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php

namespace Drupal\user\ContextProvider;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Sets the current user as a context.
 */
class CurrentUserContext implements ContextProviderInterface {

  use StringTranslationTrait;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $account;

  /**
   * The user storage.
   *
   * @var \Drupal\user\UserStorageInterface
   */
  protected $userStorage;

  /**
   * Constructs a new CurrentUserContext.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(AccountInterface $account, EntityTypeManagerInterface $entity_type_manager) {
    $this->account = $account;
    $this->userStorage = $entity_type_manager->getStorage('user');
  }

  /**
   * {@inheritdoc}
   */
  public function getRuntimeContexts(array $unqualified_context_ids) {
    $current_user = $this->userStorage->load($this->account->id());

    if ($current_user) {
      // @todo Do not validate protected fields to avoid bug in TypedData,
      //   remove this in https://www.drupal.org/project/drupal/issues/2934192.
      $current_user->_skipProtectedUserFieldConstraint = TRUE;

      $context = EntityContext::fromEntity($current_user, $this->t('Current user'));
    }
    else {
      // If not user is available, provide an empty context object.
      $context = EntityContext::fromEntityTypeId('user', $this->t('Current user'));
    }

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['user']);
    $context->addCacheableDependency($cacheability);

    $result = [
      'current_user' => $context,
    ];

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getAvailableContexts() {
    return $this->getRuntimeContexts([]);
  }

}