og-8.x-1.x-dev/src/Cache/Context/OgMembershipStateCacheContext.php
src/Cache/Context/OgMembershipStateCacheContext.php
<?php
declare(strict_types=1);
namespace Drupal\og\Cache\Context;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\og\MembershipManagerInterface;
use Drupal\og\OgContextInterface;
use Drupal\og\OgMembershipInterface;
/**
* Defines a cache context service, for "membership state" caching.
*
* Cache context ID: 'og_membership_state'
*/
class OgMembershipStateCacheContext implements CacheContextInterface {
/**
* The string to return when no context is found.
*/
const NO_CONTEXT = 'none';
public function __construct(
protected readonly AccountInterface $user,
protected readonly OgContextInterface $ogContext,
protected readonly MembershipManagerInterface $membershipManager,
) {}
/**
* {@inheritdoc}
*/
public static function getLabel() {
return new TranslatableMarkup('OG membership state');
}
/**
* {@inheritdoc}
*/
public function getContext() {
// Do not provide a cache context if there is no group in the current
// context.
$group = $this->ogContext->getGroup();
if (empty($group)) {
return self::NO_CONTEXT;
}
/** @var \Drupal\og\OgMembershipInterface $membership */
$membership = $this->membershipManager->getMembership($group, $this->user->id(), OgMembershipInterface::ALL_STATES);
return $membership ? $membership->getState() : self::NO_CONTEXT;
}
/**
* {@inheritdoc}
*/
public function getCacheableMetadata() {
return new CacheableMetadata();
}
}
