access_policy-1.0.x-dev/src/Cache/Context/UserFieldValuesCacheContext.php
src/Cache/Context/UserFieldValuesCacheContext.php
<?php namespace Drupal\access_policy\Cache\Context; use Drupal\access_policy\Session\UserFieldValuesHashGeneratorInterface; use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Cache\Context\CalculatedCacheContextInterface; use Drupal\Core\Session\AccountProxyInterface; /** * Defines the UserFieldValuesCacheContext service. * * Access rules compare values between the user and entity. That means that a * user's access is going to vary depending on their field values. If the policy * does not have access rules it will only use user.permissions. * * Cache context ID: 'user.field_values' (to vary by all observed fields of the * current user). Calculated cache context ID: 'user.field_values:%field_name', * e.g. 'user.field_value:field_department' (to vary by the values in the * department field). */ class UserFieldValuesCacheContext implements CalculatedCacheContextInterface { /** * The current user. * * @var \Drupal\Core\Session\AccountProxyInterface */ protected $currentUser; /** * The access rule manager. * * @var \Drupal\access_policy\Session\UserFieldValuesHashGeneratorInterface */ protected $hashGenerator; /** * Constructs a new UserFieldValuesCacheContext class. * * @param \Drupal\Core\Session\AccountProxyInterface $current_user * The current user. * @param \Drupal\access_policy\Session\UserFieldValuesHashGeneratorInterface $hash_generator * The user field values hash generator. */ public function __construct(AccountProxyInterface $current_user, UserFieldValuesHashGeneratorInterface $hash_generator) { $this->currentUser = $current_user; $this->hashGenerator = $hash_generator; } /** * {@inheritdoc} */ public static function getLabel() { return t("Account's fields observed by access rules."); } /** * {@inheritdoc} */ public function getContext($field_name = NULL) { return $this->hashGenerator->generate($this->currentUser, $field_name); } /** * {@inheritdoc} */ public function getCacheableMetadata($field_name = NULL) { $cacheable_metadata = new CacheableMetadata(); $tags = ['user:' . $this->currentUser->id()]; return $cacheable_metadata->setCacheTags($tags); } }