billwerk_subscriptions-1.x-dev/modules/billwerk_subscriptions_entities/billwerk_subscriptions_entities.module

modules/billwerk_subscriptions_entities/billwerk_subscriptions_entities.module
<?php

/**
 * @file
 * The ZMP Billwerk module implementing Billwerk specifics for ZMP.
 */

use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Template\Attribute;
use Drupal\billwerk_subscriptions_entities\Entity\BillwerkEntityInterface;
use Drupal\billwerk_subscriptions_entities\Entity\BillwerkFeeEntityInterface;
use Drupal\billwerk_subscriptions_entities\Entity\BillwerkSubscribeableEntityInterface;
use Drupal\user\UserInterface;

/**
 * Implements hook_theme().
 */
function billwerk_subscriptions_entities_theme(): array {
  return [
    'billwerk_plan_variant' => [
      'render element' => 'elements',
    ],
    'billwerk_component' => [
      'render element' => 'elements',
    ],
    'billwerk_plan' => [
      'render element' => 'elements',
    ],
  ];
}

/**
 * Prepares variables for billwerk plan variant templates.
 *
 * Default template: billwerk-plan-variant.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the billwerk plan variant
 *     information and any fields attached to the entity.
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_billwerk_plan_variant(array &$variables): void {
  // Add further variables:
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $entity = $variables['elements']['#billwerk_plan_variant'];
  $variables['entity'] = $entity;

  // Add classes to identify this plan variant:
  $attributes = new Attribute();
  $machineName = $entity->get('machine_name')->value ?? '';
  $attributes->addClass('billwerk-plan-variant--machine-name-' . Html::cleanCssIdentifier($machineName));
  $variables['attributes'] = $attributes;

  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

/**
 * Prepares variables for billwerk component (add-on) templates.
 *
 * Default template: billwerk-component.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the billwerk component (add-on)
 *     information and any fields attached to the entity.
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_billwerk_component(array &$variables): void {
  // Add further variables:
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $entity = $variables['elements']['#billwerk_component'];
  $variables['entity'] = $entity;

  // Add classes to identify this plan variant:
  $attributes = new Attribute();
  $machineName = $entity->get('machine_name')->value ?? '';
  $attributes->addClass('billwerk-component--machine-name-' . Html::cleanCssIdentifier($machineName));
  $variables['attributes'] = $attributes;

  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

/**
 * Prepares variables for billwerk plan templates.
 *
 * Default template: billwerk-plan.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the billwerk plan information
 *     and any fields attached to the entity.
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_billwerk_plan(array &$variables): void {
  // Add further variables:
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $entity = $variables['elements']['#billwerk_plan'];
  $variables['entity'] = $entity;

  // Add classes to identify this plan variant:
  $attributes = new Attribute();
  $machineName = $entity->get('machine_name')->value ?? '';
  $attributes->addClass('billwerk-plan--machine-name-' . Html::cleanCssIdentifier($machineName));
  $variables['attributes'] = $attributes;

  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

/**
 * Implements hook_user_cancel().
 */
function billwerk_subscriptions_entities_user_cancel($edit, UserInterface $account, $method): void {
  switch ($method) {
    case 'user_cancel_block_unpublish':
      // Unpublish billwerk plan variants.
      $storage = \Drupal::entityTypeManager()->getStorage('billwerk_plan_variant');
      $billwerk_plan_variant_ids = $storage->getQuery()
        ->condition('uid', $account->id())
        ->condition('status', 1)
        ->accessCheck(FALSE)
        ->execute();
      foreach ($storage->loadMultiple($billwerk_plan_variant_ids) as $billwerk_plan_variant) {
        /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlanVariant $billwerk_plan_variant */
        $billwerk_plan_variant->set('status', FALSE)->save();
      }

      // Unpublish billwerk component (add-on)s.
      $storage = \Drupal::entityTypeManager()->getStorage('billwerk_component');
      $billwerk_component_ids = $storage->getQuery()
        ->condition('uid', $account->id())
        ->condition('status', 1)
        ->accessCheck(FALSE)
        ->execute();
      foreach ($storage->loadMultiple($billwerk_component_ids) as $billwerk_component) {
        /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkComponent $billwerk_component */
        $billwerk_component->set('status', FALSE)->save();
      }

      // Unpublish billwerk plans.
      $storage = \Drupal::entityTypeManager()->getStorage('billwerk_plan');
      $billwerk_plan_ids = $storage->getQuery()
        ->condition('uid', $account->id())
        ->condition('status', 1)
        ->accessCheck(FALSE)
        ->execute();
      foreach ($storage->loadMultiple($billwerk_plan_ids) as $billwerk_plan) {
        /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlan $billwerk_plan */
        $billwerk_plan->set('status', FALSE)->save();
      }
      break;

    case 'user_cancel_reassign':
      // Anonymize billwerk plan variants.
      $storage = \Drupal::entityTypeManager()->getStorage('billwerk_plan_variant');
      $billwerk_plan_variant_ids = $storage->getQuery()
        ->condition('uid', $account->id())
        ->accessCheck(FALSE)
        ->execute();
      foreach ($storage->loadMultiple($billwerk_plan_variant_ids) as $billwerk_plan_variant) {
        /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlanVariant $billwerk_plan_variant */
        $billwerk_plan_variant->setOwnerId(0)->save();
      }

      // Anonymize billwerk component (add-on)s.
      $storage = \Drupal::entityTypeManager()->getStorage('billwerk_component');
      $billwerk_component_ids = $storage->getQuery()
        ->condition('uid', $account->id())
        ->accessCheck(FALSE)
        ->execute();
      foreach ($storage->loadMultiple($billwerk_component_ids) as $billwerk_component) {
        /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkComponent $billwerk_component */
        $billwerk_component->setOwnerId(0)->save();
      }

      // Anonymize billwerk plans.
      $storage = \Drupal::entityTypeManager()->getStorage('billwerk_plan');
      $billwerk_plan_ids = $storage->getQuery()
        ->condition('uid', $account->id())
        ->accessCheck(FALSE)
        ->execute();
      foreach ($storage->loadMultiple($billwerk_plan_ids) as $billwerk_plan) {
        /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlan $billwerk_plan */
        $billwerk_plan->setOwnerId(0)->save();
      }
      break;
  }
}

/**
 * Implements hook_ENTITY_TYPE_predelete() for user entities.
 */
function billwerk_subscriptions_entities_user_predelete(UserInterface $account): void {
  // Delete billwerk plan variants that belong to this account.
  /** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
  $storage = \Drupal::entityTypeManager()->getStorage('billwerk_plan_variant');
  $billwerk_plan_variant_ids = $storage->getQuery()
    ->condition('uid', $account->id())
    ->accessCheck(FALSE)
    ->execute();
  $storage->delete(
    $storage->loadMultiple($billwerk_plan_variant_ids)
  );
  // Delete old revisions.
  $billwerk_plan_variant_ids = $storage->getQuery()
    ->allRevisions()
    ->condition('uid', $account->id())
    ->accessCheck(FALSE)
    ->execute();
  foreach (array_keys($billwerk_plan_variant_ids) as $revision_id) {
    $storage->deleteRevision($revision_id);
  }

  // Delete billwerk component (add-on)s that belong to this account.
  /** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
  $storage = \Drupal::entityTypeManager()->getStorage('billwerk_component');
  $billwerk_component_ids = $storage->getQuery()
    ->condition('uid', $account->id())
    ->accessCheck(FALSE)
    ->execute();
  $storage->delete(
    $storage->loadMultiple($billwerk_component_ids)
  );
  // Delete old revisions.
  $billwerk_component_ids = $storage->getQuery()
    ->allRevisions()
    ->condition('uid', $account->id())
    ->accessCheck(FALSE)
    ->execute();
  foreach (array_keys($billwerk_component_ids) as $revision_id) {
    $storage->deleteRevision($revision_id);
  }

  // Delete billwerk plans that belong to this account.
  /** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
  $storage = \Drupal::entityTypeManager()->getStorage('billwerk_plan');
  $billwerk_plan_ids = $storage->getQuery()
    ->condition('uid', $account->id())
    ->accessCheck(FALSE)
    ->execute();
  $storage->delete(
    $storage->loadMultiple($billwerk_plan_ids)
  );
  // Delete old revisions.
  $billwerk_plan_ids = $storage->getQuery()
    ->allRevisions()
    ->condition('uid', $account->id())
    ->accessCheck(FALSE)
    ->execute();
  foreach (array_keys($billwerk_plan_ids) as $revision_id) {
    $storage->deleteRevision($revision_id);
  }
}

/**
 * Implements hook_entity_extra_field_info().
 */
function billwerk_subscriptions_entities_entity_extra_field_info() {
  $extra = [];
  $billwerkEntityTypes = [
    'billwerk_component',
    'billwerk_plan',
    'billwerk_plan_variant',
  ];
  foreach ($billwerkEntityTypes as $billwerkEntityType) {
    $extra[$billwerkEntityType][$billwerkEntityType]['display']['billwerk_subscriptions_entities_saas_product_info'] = [
      'label' => t('Billwerk ProductInfo: %type (Debug)', ['%type' => $billwerkEntityType]),
      'description' => t('Shows the Billwerk ProductInfo array for this Billwerk entity type for debugging.'),
      'weight' => 99,
      'visible' => FALSE,
    ];

    $extra[$billwerkEntityType][$billwerkEntityType]['display']['billwerk_subscriptions_entities_subscribe_button'] = [
      'label' => t('Subscribe / upgrade button'),
      'description' => t('Shows the subscribe / upgrade button'),
      'weight' => 10,
      'visible' => TRUE,
    ];

    // Only for billwerk_component and billwerk_plan_variant, which have prices:
    if (in_array($billwerkEntityType, ['billwerk_component', 'billwerk_plan_variant'])) {
      $extra[$billwerkEntityType][$billwerkEntityType]['display']['billwerk_subscriptions_entities_saas_fee_price_per_month'] = [
        'label' => t('Price per month'),
        'description' => t('Billwerk (SaaS) fee price per month value.'),
        'weight' => 20,
        'visible' => TRUE,
      ];

      $extra[$billwerkEntityType][$billwerkEntityType]['display']['billwerk_subscriptions_entities_saas_fee_price'] = [
        'label' => t('Price per period'),
        'description' => t('Billwerk (SaaS) fee price value.'),
        'weight' => 21,
        'visible' => FALSE,
      ];

      $extra[$billwerkEntityType][$billwerkEntityType]['display']['billwerk_subscriptions_entities_saas_fee_period_unit'] = [
        'label' => t('Price period unit'),
        'description' => t('Billwerk (SaaS) fee price period unit'),
        'weight' => 22,
        'visible' => FALSE,
      ];

      $extra[$billwerkEntityType][$billwerkEntityType]['display']['billwerk_subscriptions_entities_saas_fee_period_quantity'] = [
        'label' => t('Price period quantity'),
        'description' => t('Billwerk (SaaS) fee price period quantity'),
        'weight' => 23,
        'visible' => FALSE,
      ];
    }

  }
  return $extra;
}

/**
 * Implements hook_entity_view().
 */
function billwerk_subscriptions_entities_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($display->getComponent('billwerk_subscriptions_entities_saas_product_info') && $entity instanceof BillwerkEntityInterface) {
    /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkEntityInterface $entity */
    $build['billwerk_subscriptions_entities_saas_product_info'] = [
      '#type' => 'inline_template',
      '#template' => "<h2>Billwerk (SaaS) Data (Debug ProductInfo in current environment):</h2>
                      <small class=\"billwerk_subscriptions_entities_product_info\"><code><pre>{{ productInfo }}</pre></code></small>",
      '#context' => [
        'productInfo' => print_r($entity->getBillwerkProductInfo(), TRUE),
      ],
    ];
  }

  if ($display->getComponent('billwerk_subscriptions_entities_subscribe_button') && $entity instanceof BillwerkSubscribeableEntityInterface) {
    /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkSubscribeableEntityInterface $entity */
    $build['billwerk_subscriptions_entities_subscribe_button'] = $entity->buildSubscribeButton(\Drupal::currentUser(), TRUE);
  }

  if ($display->getComponent('billwerk_subscriptions_entities_saas_fee_price_per_month') && $entity instanceof BillwerkFeeEntityInterface) {
    /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkFeeEntityInterface $entity */
    $build['billwerk_subscriptions_entities_saas_fee_price_per_month'] = [
      '#markup' => billwerk_subscriptions_entities_format_price($entity->getBillwerkProductInfoRecurringPricePerMonthCents() / 100),
      '#suffix' => ' ' . t('monthly'),
    ];
  }

  if ($display->getComponent('billwerk_subscriptions_entities_saas_fee_price') && $entity instanceof BillwerkFeeEntityInterface) {
    /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkFeeEntityInterface $entity */
    $build['billwerk_subscriptions_entities_saas_fee_price'] = [
      '#markup' => billwerk_subscriptions_entities_format_price($entity->getBillwerkProductInfoRecurringPriceCents() / 100),
    ];
  }

  if ($display->getComponent('billwerk_subscriptions_entities_saas_fee_period_unit') && $entity instanceof BillwerkFeeEntityInterface) {
    /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkFeeEntityInterface $entity */
    $build['billwerk_subscriptions_entities_saas_fee_period_unit'] = [
      '#markup' => $entity->getBillwerkProductInfoRecurringPeriodUnit(),
    ];
  }

  if ($display->getComponent('billwerk_subscriptions_entities_saas_fee_period_quantity') && $entity instanceof BillwerkFeeEntityInterface) {
    /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkFeeEntityInterface $entity */
    $build['billwerk_subscriptions_entities_saas_fee_period_quantity'] = [
      '#markup' => $entity->getBillwerkProductInfoRecurringPeriodQuantity(),
    ];
  }
}

/**
 * Formats a price for display.
 *
 * @param float $amount
 *   The price amount.
 * @param string $currency
 *   The currency code.
 * @param \Drupal\Core\Session\AccountProxyInterface $account
 *   The account to get the preferred language from.
 *
 * @return string
 *   The formatted price.
 */
function billwerk_subscriptions_entities_format_price(float $amount, string $currency = 'EUR', ?AccountProxyInterface $account = NULL) {
  if ($account === NULL) {
    $account = \Drupal::currentUser();
  }
  $locale = \Drupal::service('language_manager')->getLanguage($account->getPreferredLangcode())->getId();
  $numberFormatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
  // Remove digits if zero to shorten the price:
  $numberFormatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 0);
  return $numberFormatter->formatCurrency($amount, $currency);
}

// @codingStandardsIgnoreStart
/**
 * Implements hook_ENTITY_TYPE_delete() for user_role entities.
 *
 * Removes deleted role from entities that use it.
 */
// Function billwerk_subscriptions_entities_role_delete(\Drupal\user\Entity\Role $role) {.
// @improve: Remove deleted roles from the entities!
// }
// @codingStandardsIgnoreEnd

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

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