You are here

function commerce_paypal_form_views_form_commerce_cart_form_default_alter in Commerce PayPal 8

Implements hook_form_BASE_FORM_ID_alter().

File

./commerce_paypal.module, line 32
Implements PayPal payment services for use with Drupal Commerce.

Code

function commerce_paypal_form_views_form_commerce_cart_form_default_alter(&$form, FormStateInterface $form_state, $form_id) {

  /** @var \Drupal\views\ViewExecutable $view */
  $view = reset($form_state
    ->getBuildInfo()['args']);

  // Only add the smart payment buttons if the cart form view has order items.
  if (empty($view->result)) {
    return;
  }
  $entity_type_manager = \Drupal::entityTypeManager();
  $order_id = $view->args[0];

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $entity_type_manager
    ->getStorage('commerce_order')
    ->load($order_id);

  // Skip injecting the smart payment buttons if the order total is zero or
  // negative.
  if (!$order
    ->getTotalPrice() || !$order
    ->getTotalPrice()
    ->isPositive()) {
    return;
  }

  /** @var \Drupal\commerce_payment\PaymentGatewayStorageInterface $payment_gateway_storage */
  $payment_gateway_storage = $entity_type_manager
    ->getStorage('commerce_payment_gateway');

  // Load the payment gateways. This fires an event for filtering the
  // available gateways, and then evaluates conditions on all remaining ones.
  $payment_gateways = $payment_gateway_storage
    ->loadMultipleForOrder($order);

  // Can't proceed without any payment gateways.
  if (empty($payment_gateways)) {
    return;
  }
  foreach ($payment_gateways as $payment_gateway) {
    $payment_gateway_plugin = $payment_gateway
      ->getPlugin();
    if (!$payment_gateway_plugin instanceof CheckoutInterface) {
      continue;
    }
    $config = $payment_gateway_plugin
      ->getConfiguration();

    // We only inject the Smart payment buttons on the cart page if the
    // configured payment solution is "smart_payment_buttons" and if the
    // "enable_on_cart" setting is TRUE.
    if ($payment_gateway_plugin
      ->getPaymentSolution() !== 'smart_payment_buttons' || !$config['enable_on_cart']) {
      continue;
    }

    /** @var \Drupal\commerce_paypal\SmartPaymentButtonsBuilderInterface $builder */
    $builder = \Drupal::service('commerce_paypal.smart_payment_buttons_builder');
    $form['paypal_smart_payment_buttons'] = $builder
      ->build($order, $payment_gateway, FALSE);
    break;
  }
}