contacts_subscriptions-1.x-dev/src/Form/SubscriptionActivateForm.php

src/Form/SubscriptionActivateForm.php
<?php

namespace Drupal\contacts_subscriptions\Form;

use CommerceGuys\Intl\Formatter\CurrencyFormatterInterface;
use Drupal\commerce_product\Entity\ProductVariationInterface;
use Drupal\contacts_subscriptions\InvoiceManager;
use Drupal\Core\Access\CsrfTokenGenerator;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Provides a confirmation form for activating a subscription.
 */
class SubscriptionActivateForm extends ConfirmFormBase {

  use SubscriptionFormTrait;

  /**
   * The date formatter.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected DateFormatterInterface $dateFormatter;

  /**
   * The currency formatter.
   *
   * @var \CommerceGuys\Intl\Formatter\CurrencyFormatterInterface
   */
  protected CurrencyFormatterInterface $currencyFormatter;

  /**
   * The invoice manager.
   *
   * @var \Drupal\contacts_subscriptions\InvoiceManager
   */
  protected InvoiceManager $invoiceManager;

  /**
   * SubscriptionActivateForm constructor.
   *
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter.
   * @param \CommerceGuys\Intl\Formatter\CurrencyFormatterInterface $currency_formatter
   *   The currency formatter.
   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf
   *   The CSRF token generator.
   * @param \Drupal\contacts_subscriptions\InvoiceManager $invoice_manager
   *   The invoice manager.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(DateFormatterInterface $date_formatter, CurrencyFormatterInterface $currency_formatter, CsrfTokenGenerator $csrf, InvoiceManager $invoice_manager, EntityTypeManagerInterface $entity_type_manager) {
    $this->dateFormatter = $date_formatter;
    $this->currencyFormatter = $currency_formatter;
    $this->csrf = $csrf;
    $this->invoiceManager = $invoice_manager;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $form = new static(
      $container->get('date.formatter'),
      $container->get('commerce_price.currency_formatter'),
      $container->get('csrf_token'),
      $container->get('contacts_subscriptions.invoice_manager'),
      $container->get('entity_type.manager'),
    );
    $form->logger = $container->get('logger.channel.contacts_subscriptions');
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL, ?ProductVariationInterface $commerce_product_variation = NULL, ?string $token = NULL) {
    $this->initSubscription($user, TRUE, $commerce_product_variation);

    if ($this->subscription->willRenew() && !$commerce_product_variation) {
      throw new NotFoundHttpException('Subscription is active but not switching.');
    }

    if ($commerce_product_variation != NULL && !$this->subscription->canChangeProduct()) {
      throw new AccessDeniedHttpException('Subscription cannot be changed multiple times.');
    }

    $this->initVariation($commerce_product_variation, $token, TRUE);
    $form = parent::buildForm($form, $form_state);

    $form['expiry'] = [
      '#type' => 'html_tag',
      '#tag' => 'p',
    ];
    if ($this->subscription->willRenew()) {
      $form['expiry']['#value'] = $this->t('The subscription for %org is due to renew on @date.', [
        '%org' => $this->user->label(),
        '@date' => $this->dateFormatter->format($this->subscription->getRenewalDate()->getTimestamp(), 'short_date'),
      ]);
    }
    elseif ($this->subscription->needsPaymentDetails()) {
      $expiry = $this->invoiceManager->getExpiry($this->subscription);
      $form['expiry']['#value'] = $this->t('The subscription for %org will expire on @date if not paid.', [
        '%org' => $this->user->label(),
        '@date' => $this->dateFormatter->format($expiry->getTimestamp(), 'short_date'),
      ]);
    }
    else {
      $form['expiry']['#value'] = $this->t('The subscription for %org is due to expire on @date.', [
        '%org' => $this->user->label(),
        '@date' => $this->dateFormatter->format($this->subscription->getExpiryDate()->getTimestamp(), 'short_date'),
      ]);
    }

    $form['current_product'] = [];
    $form['new_product'] = [
      '#type' => 'item',
      '#title' => $this->t('Membership:'),
      '#markup' => $this->productVariation->getProduct()->label(),
      '#wrapper_attributes' => ['class' => ['mb-0']],
    ];

    if ($this->isNewProduct) {
      $form['new_product']['#title'] = $this->t('New membership');
      $form['current_product'] = [
        '#type' => 'item',
        '#title' => $this->t('Current membership:'),
        '#markup' => $this->subscription->getProduct()->label(),
        '#wrapper_attributes' => ['class' => ['mb-0']],
      ];
    }

    $price = $this->productVariation->getPrice();
    $form['price'] = [
      '#type' => 'item',
      '#title' => $this->t('Price:'),
      '#markup' => $this->currencyFormatter->format($price->getNumber(), $price->getCurrencyCode()),
      '#wrapper_attributes' => ['class' => ['mb-0']],
    ];

    $form['renewal'] = [
      '#type' => 'item',
      '#title' => $this->t('Next renewal:'),
      '#markup' => $this->dateFormatter->format($this->subscription->getRenewalDate(FALSE)->getTimestamp(), 'short_date'),
      '#wrapper_attributes' => ['class' => ['mb-0']],
    ];
    $form['#cache'] = [
      'contexts' => ['user', 'url.query_args'],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'contacts_subscription_reactivate';
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    if ($this->subscription->willRenew()) {
      return $this->t('Are you sure you want to switch your membership?');
    }
    elseif ($this->isNewProduct) {
      return $this->t('Are you sure you want to reactivate and switch your membership?');
    }

    return $this->t('Are you sure you want to reactivate your membership?');
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    if ($this->subscription->willRenew()) {
      return $this->t('Switch membership');
    }
    elseif ($this->isNewProduct) {
      return $this->t('Reactivate & switch membership');
    }
    return $this->t('Reactivate membership');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url(
      'contacts_subscriptions.manage',
      ['user' => $this->user->id()],
    );
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $set_product = TRUE;
    $set_renewal_product = TRUE;

    if (!$this->subscription->willRenew()) {
      $this->subscription->getStatusItem()->applyTransitionById('activate');

      if ($this->isNewProduct) {
        $message = $this->t('Your membership has been reactivated and switched to %product effective immediately.', [
          '%product' => $this->productVariation->getProduct()->label(),
        ]);
      }
      else {
        $set_renewal_product = FALSE;
        $set_product = FALSE;
        $message = $this->t('Your membership has been reactivated.');
      }
    }
    else {
      $message = $this->t('Your membership has been switched to %product effective immediately.', [
        '%product' => $this->productVariation->getProduct()->label(),
      ]);
    }

    if ($set_renewal_product) {
      $this->subscription->set('renewal_product', $this->productVariation->getProductId());
    }
    if ($set_product) {
      $this->subscription->set('product', $this->productVariation->getProductId());
    }
    $this->subscription->setNewRevision();
    $this->subscription->save();

    $this->messenger()->addStatus($message);

    $form_state->setRedirectUrl(Url::fromRoute(
      'contacts_subscriptions.manage',
      ['user' => $this->user->id()],
    ));
  }

}

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

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