contacts_events-8.x-1.x-dev/src/Entity/PaymentHooks.php

src/Entity/PaymentHooks.php
<?php

namespace Drupal\contacts_events\Entity;

use Drupal\commerce_payment\Entity\PaymentInterface;
use Drupal\commerce_payment\Exception\PaymentGatewayException;
use Drupal\commerce_price\Price;

/**
 * Implementations for Payment hooks.
 */
class PaymentHooks {

  /**
   * Modify payment on creation.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentInterface $payment
   *   The payment entity.
   */
  public function create(PaymentInterface $payment) {
    // Make sure refunds are zero value with no tracking by default.
    if ($payment->getPaymentGateway()->getPluginId() === 'manual_refund') {
      if ($payment->getAmount() === NULL) {
        // Get the right currency code.
        $order = $payment->getOrder();
        if ($total = $order->getTotalPrice()) {
          $currency_code = $total->getCurrencyCode();
        }
        else {
          $currency_code = $order->getStore()->getDefaultCurrencyCode();
        }

        // Set the amount.
        $payment->setAmount(new Price('0', $currency_code));
      }
    }
  }

  /**
   * Modify payment prior to saving.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentInterface $payment
   *   The payment entity.
   * @param \Drupal\commerce_payment\Entity\PaymentInterface|null $original
   *   The original payment entity, if any.
   */
  public function preSave(PaymentInterface $payment, PaymentInterface $original = NULL) {
    if ($payment->isNew() && $payment->get('creator')->isEmpty()) {
      $payment->set('creator', \Drupal::currentUser()->id());
    }

    // Validation for manual refunds.
    $this->validateManualRefund($payment);
  }

  /**
   * Validate a manual refund payment.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentInterface $payment
   *   The payment entity.
   */
  public function validateManualRefund(PaymentInterface $payment) {
    // Don't do anything if this isn't a manual refund.
    if ($payment->getPaymentGatewayId() !== 'manual_refund') {
      return;
    }

    // Ensure the amount is negative.
    if (!$payment->getAmount()->isNegative()) {
      throw new PaymentGatewayException('Manual refunds must be for a negative amount.');
    }

    // Ensure there is no refund.
    $refund = $payment->getRefundedAmount();
    if ($refund && !$refund->isZero()) {
      throw new PaymentGatewayException('Manual refunds cannot be refunded.');
    }
  }

}

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

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