subman-1.0.x-dev/src/SubmanEmbedsHelper.php

src/SubmanEmbedsHelper.php
<?php

declare(strict_types = 1);

namespace Drupal\subman;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\subman\Exception\SubmanWebhookException;
use Drupal\user\UserInterface;

/**
 * Service for building the subman embeds, like signup forms or self service.
 */
final class SubmanEmbedsHelper {
  use StringTranslationTrait;

  /**
   * Constructs a SubmanEmbeds object.
   */
  public function __construct(
    protected readonly SubmanUtilitiesInterface $submanUtilities,
    protected readonly SubmanSync $submanSync,
  ) {}

  /**
   * Builds the signup embed render array.
   *
   * @param string $subscriptionTypeId
   *   The subscription type ID aka plan variant id.
   *
   * @return array
   *   The signup embed render array.
   */
  public function buildSignupEmbed(string $subscriptionTypeId): array {
    $build = [
      '#cache' => ['max-age' => 0],
    ];

    try {
      if (!empty($subscriptionTypeId)) {
        $pre_registration_form = $this->submanUtilities->getSetting('pre_registration_form', 'Drupal\subman\Form\PreRegistrationForm');
        if (!empty($pre_registration_form)) {
          $build['pre_registration_form'] = \Drupal::formBuilder()->getForm($pre_registration_form, $subscriptionTypeId);
        }
        else {
          $build['embed'] = $this->submanSync->buildEmbedSignup($subscriptionTypeId);
        }
      }
      else {
        $build['embed']['#markup'] = $this->t('No subscription (sub-)type ID specified');
      }
    }
    catch (SubmanWebhookException $e) {
      $this->submanUtilities->logger()->error('Exception catched to SignupBlock::build(): ' . $e->getMessage());
      $build['#markup'] = $this->t('An error occured.');
    }

    return $build;
  }

  /**
   * Shows the self service portal for all active subscriptions of the given user.
   *
   * If more than one active subscription exists, a list of subscriptions is
   * built with modal links for each subscription.
   * If only one subscription exists, the self service portal is shown directly.
   * If no subscription exists, an empty-text is shown.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user.
   *
   * @return array
   *   The render array.
   */
  public function buildSelfserviceEmbedForSubscriptions(UserInterface $user): array {
    $userSubscriptions = $this->submanSync->getUserSubscriptions($user);
    if (empty($userSubscriptions)) {
      return ['#markup' => $this->t('No active subscriptions for %username.', ['%username' => $user->getAccountName()])];
    }
    if (count($userSubscriptions) === 1) {
      // If only one subcription exists, show it directly:
      $userSubscription = array_pop($userSubscriptions);
      $subscriptionId = $userSubscription[SubmanSync::MAP_NORMALIZED_KEY][SubmanSync::MAP_NORMALIZED_SUBSCRIPTION_ID];
      return $this->buildSelfserviceEmbedForSubscription($user, $subscriptionId);
    }

    // Otherwise show a list of subscriptions to edit:
    $items = [];
    foreach ($userSubscriptions as $userSubscription) {
      $items[] = $this->buildSelfserviceModalLinkForSubscription($user, $userSubscription);
    }

    $build = [];
    $build['list'] = [
      '#cache' => ['max-age' => 0],
      'intro' => ['#markup' => $this->t('Choose one of your active subscriptions to view or change:')],
      'item_list' => [
        '#theme' => 'item_list',
        '#wrapper_attributes' => [
          'class' => [
            'subman-selfservice-subscription-list',
          ],
        ],
        '#items' => $items,
      ],
    ];

    return $build;
  }

  /**
   * Shows the self service portal for a single subscription of the given user.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user.
   * @param string $subscriptionId
   *   The subscription id.
   *
   * @return array
   *   The Drupal render array.
   */
  public function buildSelfserviceEmbedForSubscription(UserInterface $user, string $subscriptionId): array {
    $build = [];
    $userSubscriptions = $this->submanSync->getUserSubscriptions($user);
    if (empty($subscriptionId)) {
      return ['#markup' => $this->t('No valid subscription id given.')];
    }
    if (empty($userSubscriptions)) {
      return ['#markup' => $this->t('No active subscriptions for %username.', ['%username' => $user->getAccountName()])];
    }
    if (!isset($userSubscriptions[$subscriptionId])) {
      return ['#markup' => $this->t('Specified subscription is not valid for %username.', ['%username' => $user->getAccountName()])];
    }

    try {
      $build['embed'] = $this->submanSync->buildEmbedSelfservice($subscriptionId);
    }
    catch (SubmanWebhookException $e) {
      \Drupal::logger('subman')->error('Exception catched at SubmanEmbedsHelper::buildSelfserviceEmbedForSubscription(): ' . $e->getMessage(), [
        'user' => $user->getAccountName(),
        'subscriptionId' => $subscriptionId,
      ]);
      $build['#markup'] = $this->t('An error occured, please contact the administrator. We\'re sorry.');
    }
    return $build;
  }

  /**
   * Helper function to build the link for opening the self service in a modal.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The subscription owner.
   * @param array $userSubscription
   *   The subscription.
   *
   * @return array
   *   The link render array.
   */
  protected function buildSelfserviceModalLinkForSubscription(AccountInterface $account, array $userSubscription): array {
    $subscriptionId = $userSubscription[SubmanSync::MAP_NORMALIZED_KEY][SubmanSync::MAP_NORMALIZED_SUBSCRIPTION_ID];
    $linkUrl = Url::fromRoute('subman.user_selfservice_subscription', [
      'user' => $account->id(),
      'subscriptionId' => $subscriptionId,
    ]);
    if ($linkUrl->access()) {
      return [
        '#type' => 'link',
        '#title' => $this->submanSync->buildSubscriptionTitle($userSubscription),
        '#url' => $linkUrl,
        '#attributes' => [
          'class' => ['use-ajax'],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => Json::encode([
            'width' => '80%',
            'height' => 'auto',
          ]),
        ],
        '#attached' => [
          'library' => ['core/drupal.dialog.ajax'],
        ],
      ];
    }
    else {
      return [];
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc