gamify-1.1.x-dev/src/GamifyUserLinkBuilder.php
src/GamifyUserLinkBuilder.php
<?php
namespace Drupal\gamify;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;
use Drupal\user\ToolbarLinkBuilder;
use Drupal\userpoints\Service\UserPointsServiceInterface;
use Drupal\gamify\UserPointsLogService as LogService;
/**
* Class to overwrite the username in the toolbar with userpoints result.
*
* E.g. "Toni Erdmann" => "Toni Erdmann (122)"
*/
class GamifyUserLinkBuilder extends ToolbarLinkBuilder {
/**
* User points service.
*
* @var \Drupal\userpoints\Service\UserPointsServiceInterface
*/
protected UserPointsServiceInterface $userPointsService;
/**
* The current user entity.
*
* @var \Drupal\user\Entity\User|null
*/
protected ?User $user;
/**
* ToolbarHandler constructor.
*
* @param \Drupal\Core\Session\AccountProxyInterface $account
* The current user.
* @param \Drupal\userpoints\Service\UserPointsServiceInterface $user_points_service
* User points service.
*/
public function __construct(AccountProxyInterface $account, UserPointsServiceInterface $user_points_service) {
parent::__construct($account);
$this->userPointsService = $user_points_service;
$this->user = User::load($this->account->id());
}
/**
* Lazy builder callback for rendering the username.
*
* @return array
* A renderable array as expected by the renderer service.
*/
public function renderDisplayName() {
return [
'#theme' => 'gamify_toolbar_user_link',
'#display_name' => $this->account->getDisplayName(),
'#user_points' => $this->userPointsService->getPoints($this->user, LogService::DEFAULT_POINT_TYPE),
'#cache' => [
'contexts' => ['user'],
'cache_max_age' => Cache::PERMANENT,
'cache_tags' => $this->getUpCacheTags(),
],
];
}
/**
* Get UserPoints entity cache_tag.
*
* @return string[]
* Returns cache tag for userpoints result.
*/
protected function getUpCacheTags(): array {
/** @var \Drupal\userpoints\Entity\UserPointsInterface $up_id */
if ($up_id = $this->userPointsService->getPointsEntity($this->user, LogService::DEFAULT_POINT_TYPE)) {
return ["userpoints:{$up_id->id()}"];
}
return [];
}
}
