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

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,
]);
CommentFileSizeAuthor
#7 google_tag-3489811-MR101--7.patch4.04 KBanybody

Issue fork google_tag-3489811

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

ts.ag created an issue. See original summary.

anybody made their first commit to this issue’s fork.

anybody’s picture

Priority: Normal » Major

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.

anybody’s picture

Status: Active » Needs review

Maybe something like this? (See MR)

#3422723: Error: Call to a member function getCurrencyCode() on null (Drupal Commerce WSOD!) should also be applied (and merged before this one).

thomas.frobieter’s picture

Status: Needs review » Reviewed & tested by the community

Works perfectly fine.

anybody’s picture

StatusFileSize
new4.04 KB

Static patch attached until this is merged.