You are here

public function CartLinksForm::submitForm in Ubercart 8.4

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

1 call to CartLinksForm::submitForm()
CartLinksForm::buildForm in uc_cart_links/src/Form/CartLinksForm.php
Form constructor.

File

uc_cart_links/src/Form/CartLinksForm.php, line 199

Class

CartLinksForm
Preprocesses a cart link, confirming with the user for destructive actions.

Namespace

Drupal\uc_cart_links\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $cart_links_config = $this
    ->config('uc_cart_links.settings');
  $actions = explode('-', urldecode($this->actions));
  $messages = [];
  $id = $this
    ->t('(not specified)');
  $cart = $this->cartManager
    ->get();
  foreach ($actions as $action) {
    switch (mb_substr($action, 0, 1)) {

      // Set the ID of the Cart Link.
      case 'i':
      case 'I':
        $id = mb_substr($action, 1, 32);
        break;

      // Add a product to the cart.
      case 'p':
      case 'P':

        // Set the default product variables.
        $p = [
          'nid' => 0,
          'qty' => 1,
          'data' => [],
        ];
        $msg = TRUE;

        // Parse the product action to adjust the product variables.
        $parts = explode('_', $action);
        foreach ($parts as $part) {
          switch (mb_substr($part, 0, 1)) {

            // Set the product node ID: p23
            case 'p':
            case 'P':
              $p['nid'] = intval(mb_substr($part, 1));
              break;

            // Set the quantity to add to cart: _q2
            case 'q':
            case 'Q':
              $p['qty'] = intval(mb_substr($part, 1));
              break;

            // Set an attribute/option for the product: _a3o6
            case 'a':
            case 'A':
              $attribute = intval(mb_substr($part, 1, stripos($part, 'o') - 1));
              $option = (string) mb_substr($part, stripos($part, 'o') + 1);
              if (!isset($p['attributes'][$attribute])) {
                $p['attributes'][$attribute] = $option;
              }
              else {

                // Multiple options for this attribute implies checkbox
                // attribute, which we must store as an array.
                if (is_array($p['attributes'][$attribute])) {

                  // Already an array, just append this new option
                  $p['attributes'][$attribute][$option] = $option;
                }
                else {

                  // Set but not an array, means we already have at least one
                  // option, so put that into an array with this new option.
                  $p['attributes'][$attribute] = [
                    $p['attributes'][$attribute] => $p['attributes'][$attribute],
                    $option => $option,
                  ];
                }
              }
              break;

            // Suppress the add to cart message: _s
            case 's':
            case 'S':
              $msg = FALSE;
              break;
          }
        }

        // Add the item to the cart, suppressing the default redirect.
        if ($p['nid'] > 0 && $p['qty'] > 0) {

          // If it's a product kit, we need black magic to make everything
          // work right. In other words, we have to simulate FAPI's form
          // values.
          $node = Node::load($p['nid']);

          // Ensure product is 'published'.
          if ($node->status) {
            if (isset($node->products) && is_array($node->products)) {
              foreach ($node->products as $nid => $product) {
                $p['data']['products'][$nid] = [
                  'nid' => $nid,
                  'qty' => $product->qty,
                ];
              }
            }
            $cart
              ->addItem($p['nid'], $p['qty'], $p['data'] + $this->moduleHandler
              ->invokeAll('uc_add_to_cart_data', [
              $p,
            ]), $msg);
          }
          else {
            $this
              ->logger('uc_cart_link')
              ->error('Cart Link on %url tried to add an unpublished product to the cart.', [
              '%url' => $this
                ->getRequest()->server
                ->get('HTTP_REFERER'),
            ]);
          }
        }
        break;

      // Empty the shopping cart.
      case 'e':
      case 'E':
        if ($cart_links_config
          ->get('empty')) {
          $cart
            ->emptyCart();
        }
        break;

      // Display a pre-configured message.
      case 'm':
      case 'M':

        // Load the messages if they haven't been loaded yet.
        if (empty($messages)) {
          $data = explode("\n", $cart_links_config
            ->get('messages'));
          foreach ($data as $message) {

            // Skip blank lines.
            if (preg_match('/^\\s*$/', $message)) {
              continue;
            }
            list($mkey, $mdata) = explode('|', $message, 2);
            $messages[trim($mkey)] = trim($mdata);
          }
        }

        // Parse the message key and display it if it exists.
        $mkey = intval(mb_substr($action, 1));
        if (!empty($messages[$mkey])) {
          $this
            ->messenger()
            ->addMessage($messages[$mkey]);
        }
        break;
    }
  }
  if ($cart_links_config
    ->get('track')) {
    $this->database
      ->merge('uc_cart_link_clicks')
      ->key([
      'cart_link_id' => (string) $id,
    ])
      ->fields([
      'clicks' => 1,
      'last_click' => $this->dateTime
        ->getRequestTime(),
    ])
      ->expression('clicks', 'clicks + :i', [
      ':i' => 1,
    ])
      ->execute();
  }
  $this->session
    ->set('uc_cart_last_url', $this
    ->getRequest()->server
    ->get('HTTP_REFERER'));
  $query = $this
    ->getRequest()->query;
  if ($query
    ->has('destination')) {
    $options = UrlHelper::parse($query
      ->get('destination'));
    $path = $options['path'];
  }
  else {
    $path = 'cart';
    $options = [];
  }
  $options += [
    'absolute' => TRUE,
  ];

  // Form redirect is for confirmed links.
  return new RedirectResponse(Url::fromUri('base:' . $path, $options)
    ->toString());
}