AddToCartEvent WSOD for order items with no price

Created on 26 November 2024, 23 days ago

Problem/Motivation

When handling an $order_item for which the price hasn't been calculated yet, AddToCartEvent gives a fatal error:

The website encountered an unexpected error. Please try again later.
Error: Call to a member function subtract() on null in Drupal\google_tag\Plugin\GoogleTag\Event\Commerce\AddToCartEvent->getData() (line 44 of modules/contrib/google_tag/src/Plugin/GoogleTag/Event/Commerce/AddToCartEvent.php).

Related issue: RemoveFromCartEvent occasionally WSOD 🐛 RemoveFromCartEvent occasionally WSOD Active

Steps to reproduce

Execute something like \Drupal::service('commerce_cart.cart_manager')->addOrderItem($cart, $order_item); with:

$order_item = OrderItem::create([
  'type' => 'default',
  'purchased_entity' => $variation->id(),
  'quantity' => 1,
]);
🐛 Bug report
Status

Active

Version

2.0

Component

Code

Created by

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

  • Issue created by @ts.ag
  • First commit to issue fork.
  • 🇩🇪Germany Anybody Porta Westfalica

    This is the related code:

    public function getData(): array {
        // @todo leverage config for token replacement.
        $order_item = $this->getContextValue('item');
        assert($order_item instanceof OrderItemInterface);
        $unit_price = $order_item->getUnitPrice();
        assert($unit_price !== NULL);
        $adjusted_price = $order_item->getAdjustedUnitPrice();
        assert($adjusted_price !== NULL);
    
        $item_data = [
          'item_name' => $order_item->label(),
          'affiliation' => $order_item->getOrder()->getStore()->label(),
          'discount' => $unit_price->subtract($adjusted_price)->getNumber(),
          'price' => $this->formatPriceNumber($unit_price),
          'quantity' => (int) $order_item->getQuantity(),
        ];
    

    assert($unit_price !== NULL); safes us in dev, but not in prod, I guess?

    We maybe this needs more defensive checking also for production?
    This is major for Drupal Commerce projects.

  • 🇩🇪Germany Anybody Porta Westfalica

    Maybe something like this? (See MR)

    🐛 Call to a member function getCurrencyCode() on null Active should also be applied (and merged before this one).

  • Pipeline finished with Success
    about 2 hours ago
    #373880
Production build 0.71.5 2024