You are here

class UserAchievements in Opigno statistics 3.x

User achievements page controller.

@package Drupal\opigno_statistics\Controller

Hierarchy

Expanded class hierarchy of UserAchievements

File

src/Controller/UserAchievements.php, line 22

Namespace

Drupal\opigno_statistics\Controller
View source
class UserAchievements extends ControllerBase {

  /**
   * Completed trainings tab machine name.
   */
  const TRANINGS_TAB = 'trainings';

  /**
   * Certificates tab machine name.
   */
  const CERTIFICATES_TAB = 'certificates';

  /**
   * Badges tab machine name.
   */
  const BADGES_TAB = 'badges';

  /**
   * Skills tab machine name.
   */
  const SKILLS_TAB = 'skills';

  /**
   * Opigno user statistics manager service.
   *
   * @var \Drupal\opigno_statistics\Services\UserStatisticsManager
   */
  protected $statsManager;

  /**
   * The CSRF token generator service.
   *
   * @var \Drupal\Core\Access\CsrfTokenGenerator
   */
  protected $csrfToken;

  /**
   * UserAchievements constructor.
   *
   * @param \Drupal\opigno_statistics\Services\UserStatisticsManager $stats_manager
   *   Opigno user statistics manager service.
   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token
   *   The CSRF token generator service.
   */
  public function __construct(UserStatisticsManager $stats_manager, CsrfTokenGenerator $csrf_token) {
    $this->statsManager = $stats_manager;
    $this->csrfToken = $csrf_token;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('opigno_statistics.user_stats_manager'), $container
      ->get('csrf_token'));
  }

  /**
   * Build the user achievements page content.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   * @param \Drupal\user\UserInterface $user
   *   The user to get achievements of.
   *
   * @return array
   *   The render array to display the achievements page content.
   */
  public function achievementsPage(Request $request, UserInterface $user) : array {
    $uid = (int) $user
      ->id();
    $active_tab = $request
      ->get('tab', 'trainings');

    // Build tabs section structure.
    $tabs = [];
    $names = [
      static::TRANINGS_TAB,
      static::CERTIFICATES_TAB,
      static::BADGES_TAB,
      static::SKILLS_TAB,
    ];
    foreach ($names as $name) {
      $params = [
        'user' => $uid,
        'tab' => $name,
      ];
      $url = Url::fromRoute('opigno_statistics.switch_achievement_tabs', $params);
      $internal = $url
        ->getInternalPath();
      $url
        ->setOption('query', [
        'token' => $this->csrfToken
          ->get($internal),
      ]);
      $tabs[$name] = [
        'title' => $this
          ->getTabTitle($name),
        'url' => $url
          ->toString(),
      ];
    }

    // Add the sharable post url if socials enabled.
    $attached = [];
    if ($this->statsManager->isSocialsEnabled) {
      $share_url = Url::fromRoute('opigno_social.share_post_content')
        ->toString();
      $attached = [
        'library' => [
          'opigno_social/post_sharing',
        ],
        'drupalSettings' => [
          'opignoSocial' => [
            'shareContentUrl' => $share_url instanceof GeneratedUrl ? $share_url
              ->getGeneratedUrl() : $share_url,
          ],
        ],
      ];
    }
    return [
      '#theme' => 'opigno_user_achievements_page',
      '#tabs' => $tabs,
      '#active' => $active_tab,
      '#content' => $this
        ->getTabContent($uid, $active_tab),
      '#attached' => $attached,
    ];
  }

  /**
   * Get the tab title.
   *
   * @param string $tab
   *   The tab machine name to get the title for.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup|string
   *   The tab title.
   */
  private function getTabTitle(string $tab) {
    $titles = [
      static::TRANINGS_TAB => $this
        ->t('Trainings completed'),
      static::CERTIFICATES_TAB => $this
        ->t('Certificates'),
      static::BADGES_TAB => $this
        ->t('Badges'),
      static::SKILLS_TAB => $this
        ->t('Skills'),
    ];
    return $titles[$tab] ?? '';
  }

  /**
   * Build the content depending on the given tab name.
   *
   * @param int $uid
   *   The user ID to get the tab content for.
   * @param string $tab
   *   The tab machine name to get the content for.
   *
   * @return array
   *   The render array to display the tab content.
   */
  private function getTabContent(int $uid, string $tab) : array {
    switch ($tab) {
      case static::CERTIFICATES_TAB:
        $content = $this->statsManager
          ->buildCertificatesList($uid);
        break;
      case static::BADGES_TAB:
        $content = $this->statsManager
          ->buildBadgesList($uid);
        break;
      case static::SKILLS_TAB:
        $content = $this->statsManager
          ->buildSkillsList($uid);
        break;
      default:
        $content = $this->statsManager
          ->buildTrainingsList($uid, TRUE);
    }
    return $content;
  }

  /**
   * Ajax callback to swith tabs content.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user to render the content for.
   * @param string $tab
   *   The tab machine name to be displayed.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The ajax response to display the tab content.
   */
  public function switchTabs(UserInterface $user, string $tab) : AjaxResponse {
    $uid = (int) $user
      ->id();
    $content = $this
      ->getTabContent($uid, $tab);
    $title = $this
      ->getTabTitle($tab);

    // Update the title, the content and the active tab.
    $response = new AjaxResponse();
    $response
      ->addCommand(new HtmlCommand('#opigno-achievements-content h2', $title));
    $response
      ->addCommand(new HtmlCommand('#opigno-achievements-content .tab-content', $content));
    $response
      ->addCommand(new InvokeCommand('.achievements-tabs a', 'removeClass', [
      'active',
    ]));
    $response
      ->addCommand(new InvokeCommand(".achievements-tabs a.{$tab}", 'addClass', [
      'active',
    ]));
    return $response;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UserAchievements::$csrfToken protected property The CSRF token generator service.
UserAchievements::$statsManager protected property Opigno user statistics manager service.
UserAchievements::achievementsPage public function Build the user achievements page content.
UserAchievements::BADGES_TAB constant Badges tab machine name.
UserAchievements::CERTIFICATES_TAB constant Certificates tab machine name.
UserAchievements::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
UserAchievements::getTabContent private function Build the content depending on the given tab name.
UserAchievements::getTabTitle private function Get the tab title.
UserAchievements::SKILLS_TAB constant Skills tab machine name.
UserAchievements::switchTabs public function Ajax callback to swith tabs content.
UserAchievements::TRANINGS_TAB constant Completed trainings tab machine name.
UserAchievements::__construct public function UserAchievements constructor.