You are here

abstract class PaymentMethodBase in Payment 8.2

A base payment method plugin.

Plugins that extend this class must have the following two keys in their plugin definitions:

  • message_text: The translated human-readable text to display in the payment form.
  • message_text_format: The ID of the text format to format message_text with.

Hierarchy

Expanded class hierarchy of PaymentMethodBase

2 files declare their use of PaymentMethodBase
PaymentMethodBaseTest.php in tests/src/Unit/Plugin/Payment/Method/PaymentMethodBaseTest.php
PaymentTestNoResponse.php in modules/payment_test/src/Plugin/Payment/Method/PaymentTestNoResponse.php

File

src/Plugin/Payment/Method/PaymentMethodBase.php, line 32

Namespace

Drupal\payment\Plugin\Payment\Method
View source
abstract class PaymentMethodBase extends PluginBase implements ContainerFactoryPluginInterface, PaymentMethodInterface, PaymentMethodCapturePaymentInterface, PaymentMethodRefundPaymentInterface, PluginFormInterface, CacheableDependencyInterface, ConfigurableInterface, DependentPluginInterface {
  use PaymentAwareTrait;

  /**
   * The event dispatcher.
   *
   * @var \Drupal\payment\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The token API.
   *
   * @var \Drupal\Core\Utility\Token
   */
  protected $token;

  /**
   * Constructs a new instance.
   *
   * @param mixed[] $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed[] $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\payment\EventDispatcherInterface $event_dispatcher
   *   The event dispatcher.
   * @param \Drupal\Core\Utility\Token $token
   *   The token API.
   * @param \Drupal\payment\Plugin\Payment\Status\PaymentStatusManagerInterface
   *   The payment status manager.
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, ModuleHandlerInterface $module_handler, EventDispatcherInterface $event_dispatcher, Token $token, PaymentStatusManagerInterface $payment_status_manager) {
    $configuration += $this
      ->defaultConfiguration();
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->eventDispatcher = $event_dispatcher;
    $this->moduleHandler = $module_handler;
    $this->paymentStatusManager = $payment_status_manager;
    $this->token = $token;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('module_handler'), $container
      ->get('payment.event_dispatcher'), $container
      ->get('token'), $container
      ->get('plugin.manager.payment.status'));
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {

    // The default payment method manager caches definitions using the
    // "payment_method" tag.
    return [
      'payment_method',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return Cache::PERMANENT;
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    return $this->configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
    $this->configuration = $configuration + $this
      ->defaultConfiguration();
  }

  /**
   * Gets the payer message text.
   *
   * @return string
   */
  public function getMessageText() {
    return $this->pluginDefinition['message_text'];
  }

  /**
   * Gets the payer message text format.
   *
   * @return string
   */
  public function getMessageTextFormat() {
    return $this->pluginDefinition['message_text_format'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $message_text = $this->token
      ->replace($this
      ->getMessageText(), array(
      'payment' => $this
        ->getPayment(),
    ), array(
      'clear' => TRUE,
    ));
    if ($this->moduleHandler
      ->moduleExists('filter')) {
      $elements['message'] = array(
        '#type' => 'processed_text',
        '#text' => $message_text,
        '#format' => $this
          ->getMessageTextFormat(),
      );
    }
    else {
      $elements['message'] = array(
        '#type' => 'markup',
        '#markup' => $message_text,
      );
    }
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function executePaymentAccess(AccountInterface $account) {
    if (!$this
      ->getPayment()) {
      throw new \LogicException('Trying to check access for a non-existing payment. A payment must be set trough self::setPayment() first.');
    }
    return AccessResult::allowedIf($this->pluginDefinition['active'])
      ->andIf($this
      ->executePaymentAccessCurrency($account))
      ->andIf($this->eventDispatcher
      ->executePaymentAccess($this
      ->getPayment(), $this, $account))
      ->andIf($this
      ->doExecutePaymentAccess($account))
      ->addCacheableDependency($this
      ->getPayment())
      ->addCacheTags([
      'payment_method',
    ]);
  }

  /**
   * Performs a payment method-specific access check for payment execution.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   */
  protected function doExecutePaymentAccess(AccountInterface $account) {
    return AccessResult::allowed();
  }

  /**
   * {@inheritdoc}
   */
  public function executePayment() {
    if (!$this
      ->getPayment()) {
      throw new \LogicException('Trying to execute a non-existing payment. A payment must be set trough self::setPayment() first.');
    }
    $this->eventDispatcher
      ->preExecutePayment($this
      ->getPayment());
    $this->payment
      ->setPaymentStatus($this->paymentStatusManager
      ->createInstance('payment_pending'));
    $this
      ->doExecutePayment();
    $this
      ->getPayment()
      ->save();
    return $this
      ->getPaymentExecutionResult();
  }

  /**
   * Performs the actual payment execution.
   */
  protected function doExecutePayment() {

    // This method is empty so child classes can override it and provide their
    // own implementation.
  }

  /**
   * {@inheritdoc}
   */
  public function getPaymentExecutionResult() {
    return new OperationResult();
  }

  /**
   * {@inheritdoc}
   */
  public function capturePaymentAccess(AccountInterface $account) {
    if (!$this
      ->getPayment()) {
      throw new \LogicException('Trying to check access for a non-existing payment. A payment must be set trough self::setPayment() first.');
    }
    return $this
      ->doCapturePaymentAccess($account);
  }

  /**
   * Performs a payment method-specific access check for payment capture.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *
   * @return bool
   */
  protected function doCapturePaymentAccess(AccountInterface $account) {

    // Child classes must override this method to support payment capture.
    return AccessResult::forbidden();
  }

  /**
   * {@inheritdoc}
   */
  public function capturePayment() {
    if (!$this
      ->getPayment()) {
      throw new \LogicException('Trying to capture a non-existing payment. A payment must be set trough self::setPayment() first.');
    }
    $this->eventDispatcher
      ->preCapturePayment($this
      ->getPayment());
    $this
      ->doCapturePayment();
    return $this
      ->getPaymentCaptureResult();
  }

  /**
   * {@inheritdoc}
   */
  public function getPaymentCaptureResult() {
    return new OperationResult();
  }

  /**
   * Performs the actual payment capture.
   */
  protected function doCapturePayment() {
    throw new \Exception('Child classes must override this method to support payment capture.');
  }

  /**
   * {@inheritdoc}
   */
  public function refundPaymentAccess(AccountInterface $account) {
    if (!$this
      ->getPayment()) {
      throw new \LogicException('Trying to check access for a non-existing payment. A payment must be set trough self::setPayment() first.');
    }
    return $this
      ->doRefundPaymentAccess($account);
  }

  /**
   * Performs a payment method-specific access check for payment refunds.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *
   * @return bool
   */
  protected function doRefundPaymentAccess(AccountInterface $account) {

    // Child classes must override this method to support payment refund.
    return AccessResult::forbidden();
  }

  /**
   * {@inheritdoc}
   */
  public function refundPayment() {
    if (!$this
      ->getPayment()) {
      throw new \LogicException('Trying to refund a non-existing payment. A payment must be set trough self::setPayment() first.');
    }
    $this->eventDispatcher
      ->preRefundPayment($this
      ->getPayment());
    $this
      ->doRefundPayment();
    return $this
      ->getPaymentRefundResult();
  }

  /**
   * {@inheritdoc}
   */
  public function getPaymentRefundResult() {
    return new OperationResult();
  }

  /**
   * Performs the actual payment refund.
   */
  protected function doRefundPayment() {
    throw new \Exception('Child classes must override this method to support payment refund.');
  }

  /**
   * Checks a payment's currency against this plugin.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   */
  protected function executePaymentAccessCurrency(AccountInterface $account) {
    $supported_currencies = $this
      ->getSupportedCurrencies();
    $payment_currency_code = $this
      ->getPayment()
      ->getCurrencyCode();
    $payment_amount = $this
      ->getPayment()
      ->getAmount();

    // If all currencies are allowed, grant access.
    if ($supported_currencies === TRUE) {
      return AccessResult::allowed();
    }

    // If the payment's currency is not specified, access is denied.
    foreach ($supported_currencies as $supported_currency) {
      if ($supported_currency
        ->getCurrencyCode() != $payment_currency_code) {
        continue;
      }
      elseif ($supported_currency
        ->getMinimumAmount() && $payment_amount < $supported_currency
        ->getMinimumAmount()) {
        return AccessResult::forbidden();
      }
      elseif ($supported_currency
        ->getMaximumAmount() && $payment_amount > $supported_currency
        ->getMaximumAmount()) {
        return AccessResult::forbidden();
      }
      else {
        return AccessResult::allowed();
      }
    }
    return AccessResult::forbidden();
  }

  /**
   * Returns the supported currencies.
   *
   * @return \Drupal\payment\Plugin\Payment\Method\SupportedCurrencyInterface[]|true
   *   Return TRUE to allow all currencies and amounts.
   */
  protected abstract function getSupportedCurrencies();

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PaymentAwareTrait::$payment protected property The payment.
PaymentAwareTrait::getPayment public function
PaymentAwareTrait::setPayment public function
PaymentMethodBase::$eventDispatcher protected property The event dispatcher.
PaymentMethodBase::$moduleHandler protected property The module handler.
PaymentMethodBase::$token protected property The token API.
PaymentMethodBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
PaymentMethodBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
PaymentMethodBase::capturePayment public function Captures the payment. Overrides PaymentMethodCapturePaymentInterface::capturePayment
PaymentMethodBase::capturePaymentAccess public function Checks if the payment can be captured. Overrides PaymentMethodCapturePaymentInterface::capturePaymentAccess
PaymentMethodBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 1
PaymentMethodBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration
PaymentMethodBase::doCapturePayment protected function Performs the actual payment capture. 2
PaymentMethodBase::doCapturePaymentAccess protected function Performs a payment method-specific access check for payment capture. 2
PaymentMethodBase::doExecutePayment protected function Performs the actual payment execution. 2
PaymentMethodBase::doExecutePaymentAccess protected function Performs a payment method-specific access check for payment execution.
PaymentMethodBase::doRefundPayment protected function Performs the actual payment refund. 2
PaymentMethodBase::doRefundPaymentAccess protected function Performs a payment method-specific access check for payment refunds. 2
PaymentMethodBase::executePayment public function Executes the payment. Overrides PaymentMethodInterface::executePayment
PaymentMethodBase::executePaymentAccess public function Checks if the payment can be executed. Overrides PaymentMethodInterface::executePaymentAccess
PaymentMethodBase::executePaymentAccessCurrency protected function Checks a payment's currency against this plugin.
PaymentMethodBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
PaymentMethodBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge
PaymentMethodBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags
PaymentMethodBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
PaymentMethodBase::getMessageText public function Gets the payer message text.
PaymentMethodBase::getMessageTextFormat public function Gets the payer message text format.
PaymentMethodBase::getPaymentCaptureResult public function Gets the payment capture status. Overrides PaymentMethodCapturePaymentInterface::getPaymentCaptureResult
PaymentMethodBase::getPaymentExecutionResult public function Gets the payment execution status. Overrides PaymentMethodInterface::getPaymentExecutionResult 1
PaymentMethodBase::getPaymentRefundResult public function Gets the payment refund status. Overrides PaymentMethodRefundPaymentInterface::getPaymentRefundResult
PaymentMethodBase::getSupportedCurrencies abstract protected function Returns the supported currencies. 2
PaymentMethodBase::refundPayment public function Refunds the payment. Overrides PaymentMethodRefundPaymentInterface::refundPayment
PaymentMethodBase::refundPaymentAccess public function Checks if the payment can be refunded. Overrides PaymentMethodRefundPaymentInterface::refundPaymentAccess
PaymentMethodBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
PaymentMethodBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
PaymentMethodBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
PaymentMethodBase::__construct public function Constructs a new instance. Overrides PluginBase::__construct 1
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.