billwerk_subscriptions-1.x-dev/modules/billwerk_subscriptions_entities/src/Entity/BillwerkPlan.php

modules/billwerk_subscriptions_entities/src/Entity/BillwerkPlan.php
<?php

declare(strict_types=1);

namespace Drupal\billwerk_subscriptions_entities\Entity;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;

/**
 * Defines the Billwerk Plan entity class.
 *
 * @ContentEntityType(
 *   id = "billwerk_plan",
 *   label = @Translation("Billwerk Plan"),
 *   label_collection = @Translation("Billwerk Plans"),
 *   label_singular = @Translation("Billwerk Plan"),
 *   label_plural = @Translation("Billwerk Plans"),
 *   label_count = @PluralTranslation(
 *     singular = "@count Billwerk Plans",
 *     plural = "@count Billwerk Plans",
 *   ),
 *   handlers = {
 *     "list_builder" = "Drupal\billwerk_subscriptions_entities\BillwerkPlanListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" = "Drupal\billwerk_subscriptions_entities\BillwerkPlanAccessControlHandler",
 *     "form" = {
 *       "add" = "Drupal\billwerk_subscriptions_entities\Form\BillwerkPlanForm",
 *       "edit" = "Drupal\billwerk_subscriptions_entities\Form\BillwerkPlanForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *       "delete-multiple-confirm" = "Drupal\Core\Entity\Form\DeleteMultipleForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "billwerk_plan",
 *   data_table = "billwerk_plan_field_data",
 *   revision_table = "billwerk_plan_revision",
 *   revision_data_table = "billwerk_plan_field_revision",
 *   show_revision_ui = TRUE,
 *   translatable = TRUE,
 *   admin_permission = "administer billwerk_plan",
 *   entity_keys = {
 *     "id" = "id",
 *     "revision" = "revision_id",
 *     "langcode" = "langcode",
 *     "label" = "label",
 *     "uuid" = "uuid",
 *     "owner" = "uid",
 *     "machine_name" = "machine_name",
 *     "hidden" = "hidden",
 *     "weight" = "weight",
 *     "billwerk_id_production" = "billwerk_id_production",
 *     "billwerk_id_sandbox" = "billwerk_id_sandbox",
 *   },
 *   revision_metadata_keys = {
 *     "revision_user" = "revision_uid",
 *     "revision_created" = "revision_timestamp",
 *     "revision_log_message" = "revision_log",
 *   },
 *   links = {
 *     "collection" = "/admin/content/billwerk/plan",
 *     "add-form" = "/admin/content/billwerk/plan/add",
 *     "canonical" = "/admin/content/billwerk/plan/{billwerk_plan}",
 *     "edit-form" = "/admin/content/billwerk/plan/{billwerk_plan}/edit",
 *     "delete-form" = "/admin/content/billwerk/plan/{billwerk_plan}/delete",
 *     "delete-multiple-form" = "/admin/content/billwerk/plan/delete-multiple",
 *   },
 *   field_ui_base_route = "entity.billwerk_plan.settings",
 * )
 */
final class BillwerkPlan extends BillwerkEntityAbstract implements BillwerkEntityInterface {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {

    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setLabel(t('Label'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['machine_name'] = BaseFieldDefinition::create('string')
      ->setRevisionable(TRUE)
      ->setTranslatable(FALSE)
      ->setLabel(t('Machine name'))
      ->setDescription(t('The human readable machine name, typically set as external_id at Billwerk.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 256)
      ->addConstraint('UniqueField', [])
      ->addPropertyConstraints('value', ['Regex' => ['pattern' => '/^[a-z0-9_]+$/']])
      ->setDisplayOptions('form', [
        'type' => 'machine_name',
        'weight' => -5,
        'settings' => [
          'source_field' => 'label',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -5,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setRevisionable(TRUE)
      ->setLabel(t('Status'))
      ->setDefaultValue(TRUE)
      ->setSetting('on_label', 'Enabled')
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => FALSE,
        ],
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'boolean',
        'label' => 'above',
        'weight' => -4,
        'settings' => [
          'format' => 'enabled-disabled',
        ],
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['hidden'] = BaseFieldDefinition::create('boolean')
      ->setRevisionable(TRUE)
      ->setLabel(t('Hidden'))
      ->setDescription(t('Allows hiding plans that are available, but should not be shown for (public) booking'))
      ->setDefaultValue(FALSE)
      ->setSetting('on_label', 'Hidden')
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => FALSE,
        ],
        'weight' => -3,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'boolean',
        'label' => 'above',
        'weight' => -3,
        'settings' => [
          'format' => 'enabled-disabled',
        ],
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['weight'] = BaseFieldDefinition::create('integer')
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setLabel(t('Weight'))
      ->setDescription(t('The weight in lists and tables. Lower weight is shown more prominent (top).'))
      ->setDisplayOptions('form', [
        'type' => 'number',
        'weight' => -2,
      ])
      ->setDefaultValue(0)
      ->setRequired(TRUE)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'number_integer',
        'label' => 'above',
        'weight' => -2,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['billwerk_id_production'] = BaseFieldDefinition::create('string')
      ->setRevisionable(TRUE)
      ->setTranslatable(FALSE)
      ->setLabel(t('Billwerk ID (Production)'))
      ->setDescription(t('The ID from Billwerk for this plan from the <em>production</em> environment. Connects the entity with the saas record.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -1,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['billwerk_id_sandbox'] = BaseFieldDefinition::create('string')
      ->setRevisionable(TRUE)
      ->setTranslatable(FALSE)
      ->setLabel(t('Billwerk ID (Sandbox)'))
      ->setDescription(t('The ID from Billwerk for this plan from the <em>sandbox</em> environment. Connects the entity with the saas record.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 0,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['description'] = BaseFieldDefinition::create('text_long')
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setLabel(t('Description'))
      ->setDisplayOptions('form', [
        'type' => 'text_textarea',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'text_default',
        'label' => 'above',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setLabel(t('Author'))
      ->setSetting('target_type', 'user')
      ->setDefaultValueCallback(self::class . '::getDefaultEntityOwner')
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => 60,
          'placeholder' => '',
        ],
        'weight' => 15,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'author',
        'weight' => 15,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setTranslatable(TRUE)
      ->setDescription(t('The time that the Billwerk Plan was created.'))
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'timestamp',
        'weight' => 20,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('form', [
        'type' => 'datetime_timestamp',
        'weight' => 20,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setTranslatable(TRUE)
      ->setDescription(t('The time that the Billwerk Plan was last edited.'));

    return $fields;
  }

  /**
   * Returns the features taxonomy terms array.
   *
   * @return array
   *   The features taxonomy terms array.
   */
  public function getFeatures(): array {
    return $this->get('field_features')->referencedEntities();
  }

  /**
   * {@inheritDoc}
   */
  protected function getBillwerkProductInfoType(): string {
    return 'Plans';
  }

  /**
   * Returns the BillwerkPlanVariants assigned to this plan.
   *
   * @return array
   *   The BillwerkPlanVariants assigned to this plan.
   */
  public function getBillwerkPlanVariants(bool $enabled = TRUE, $onlyVisible = TRUE): array {
    $billwerkPlanVariantStorage = $this->entityTypeManager()->getStorage('billwerk_plan_variant');
    $query = $billwerkPlanVariantStorage->getQuery()
      ->condition('status', $enabled)
      ->condition('field_billwerk_plan', $this->id())
      ->sort('weight', 'ASC')
      ->accessCheck(TRUE);
    if ($onlyVisible) {
      // Filter hidden (otherwise do not use this filter):
      $query->condition('hidden', FALSE);
    }
    $results = $query->execute();
    return !empty($results) ? $billwerkPlanVariantStorage->loadMultiple($results) : [];
  }

  /**
   * {@inheritDoc}
   */
  public function buildSubscribeButton(
    AccountProxyInterface $user,
    bool $modal = FALSE,
    array $additionalClasses = ['secondary', 'expanded'],
  ): array {
    $build = [];

    // Anonymous user always see the trial button for all plans:
    if ($user->isAnonymous()) {
      $build = [
        '#type' => 'link',
        '#title' => $this->t('Try for free now!'),
        '#url' => Url::fromRoute('user.register'),
        '#attributes' => [
          'class' => ['button', ...$additionalClasses],
        ],
      ];
    }
    else {
      $build = [
        '#type' => 'link',
        '#title' => $this->t('Manage subscriptions'),
        '#url' => Url::fromRoute('billwerk_subscriptions_manage.current_user_subscription', [], [
          'query' => [
            // This parameter isn't used yet:
            'plan' => $this->getMachineName(),
          ],
        ]),
        '#attributes' => [
          'class' => ['button', ...$additionalClasses],
        ],
      ];
    }

    // Add modal, if enabled:
    if ($modal && !empty($build)) {
      // Add modal classes and library, if enabled:
      $build['#attributes']['class'][] = 'use-ajax';
      $build['#attributes']['data-dialog-type'] = 'modal';
      $build['#attached']['library'][] = 'core/drupal.dialog.ajax';
    }

    // Cache by user.
    $build['#cache']['contexts'][] = 'user';

    // Add the cacheable dependencies:
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($build, $user);
    $renderer->addCacheableDependency($build, $this);

    return $build;
  }

}

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

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