---
title: Cart Debugging and Troubleshooting | Shopware Community Hub
description: >-
  Learn how to debug cart issues, analyze performance, and troubleshoot common
  checkout problems.
canonical_url: 'https://hub.shopware.com/learn/unit/cart-debugging-troubleshooting'
---

# Cart Debugging and Troubleshooting

<LearningObjectives>

- Use debugging tools to inspect cart state and cart calculation steps.
- Analyze cart performance and identify potential bottlenecks.
- Troubleshoot common cart and checkout-related issues.
- Implement logging and monitoring for cart operations for better observability.

</LearningObjectives>

# Cart Debugging and Troubleshooting

Cart debugging can be challenging because the cart calculation is not a single step. Multiple collectors, processors, and validators work together and interact during recalculations. When something goes wrong, it's not always obvious where the problem lies.

This learning unit will show you practical debugging techniques using real examples from our `AcademyCartExamples` plugin.

## The Symfony Debug Toolbar: Your First Line of Defense

The Symfony debug toolbar is one of the most powerful tools for cart debugging. When you're in development mode, it provides a cart sidebar that shows detailed information about the current cart state.

![Symfony Debug Toolbar Cart Sidebar](assets/cartSidebarEntry-symfonyDebugConsole.jpg)

The cart sidebar displays:

- **Line items** with quantities, unit prices, and total prices
- **Financial breakdown** including subtotal, shipping, and VAT
- **Line item types** for example product, promotion or credit
- **Cart totals** and pricing details
- **Active cart services** showing collectors and processors with their priorities
- **Request information** including method, URL, and response status

This gives you an immediate overview of what's happening in the cart without needing to dig into logs or database queries.

## Debugging the Bulk Discount Processor

Let's walk through debugging our `BulkDiscountProcessor` when it's not working as expected.

Imagine you've implemented the cart processor correctly, but customers aren't seeing any discounts.

### Step 1: Check the Symfony Debug Toolbar

First, open the cart page and check the Symfony debug toolbar. Look for:

- Are line items showing the expected quantities?
- Is the customer context correct (B2B vs. B2C)?
- Are there any error messages?
- Is the `BulkDiscountProcessor` under Cart Services -> Processors?

### Step 2: Enable Detailed Logging

Add logging to your processor to see what's happening:

```php
// In BulkDiscountProcessor.php
public function process(
    CartDataCollection $data,
    Cart $original,
    Cart $toCalculate,
    SalesChannelContext $context,
    CartBehavior $behavior
): void {
    $this->logger->info('BulkDiscountProcessor: Starting processing', [
        'customer_id' => $context->getCustomer()?->getId(),
        'is_b2b' => $this->isB2BCustomer($context),
        'line_items_count' => $toCalculate->getLineItems()->count()
    ]);

    // Only apply to B2B customers
    if (!$this->isB2BCustomer($context)) {
        $this->logger->info('BulkDiscountProcessor: Skipping - not B2B customer');
        return;
    }

    $lineItems = $toCalculate->getLineItems();
    $totalQuantity = $this->calculateTotalQuantity($lineItems);
    
    $this->logger->info('BulkDiscountProcessor: Calculated total quantity', [
        'total_quantity' => $totalQuantity
    ]);

    // Apply bulk discount based on quantity
    $discountPercentage = $this->getBulkDiscountPercentage($totalQuantity);
    
    $this->logger->info('BulkDiscountProcessor: Discount percentage', [
        'discount_percentage' => $discountPercentage
    ]);

    if ($discountPercentage > 0) {
        $this->applyBulkDiscount($lineItems, $discountPercentage, $context);
        $this->logger->info('BulkDiscountProcessor: Applied discount successfully');
    }
}
```

This makes the processor's decision path visible and helps you understand why it runs or why it doesn't.

### Step 3: Check the Logs

Now check your logs to see what's happening:

```bash
tail -f var/log/dev.log | grep "BulkDiscountProcessor"
```

You might see output like:

```txt
[2024-01-15 10:30:15] app.INFO: BulkDiscountProcessor: Starting processing {"customer_id":"123","is_b2b":true,"line_items_count":2}
[2024-01-15 10:30:15] app.INFO: BulkDiscountProcessor: Calculated total quantity {"total_quantity":20}
[2024-01-15 10:30:15] app.INFO: BulkDiscountProcessor: Discount percentage {"discount_percentage":5}
[2024-01-15 10:30:15] app.INFO: BulkDiscountProcessor: Applied discount successfully
```

From this output, you can clearly see:

- The cart processor is executed.
- The customer is a B2B customer.
- The quantity threshold is reached.
- The discount is applied successfully.

If any of these steps is missing, the issue is likely logic-related, not configuration-related.

### Step 4: Verify Your Cart Processor in the Runtime Flow

When debugging cart processors, focus on how they are integrated into the cart lifecycle.

A cart processor is part of the runtime flow and must be verified there. Start with these checks:

**1. Service registration**

Make sure your processor is registered correctly in the `services.xml` file.

```xml
<service id="Swag\BasicExample\Core\Checkout\Cart\CustomCartProcessor">
    <tag name="shopware.cart.processor"/>
</service>
```

If this tag is missing or incorrect, your processor won't be executed.

**2. Runtime flow**

Set a breakpoint or add logging inside your processor. Then trigger a cart action (e.g., add product, change quantity). If you do not see your output, your processor is not part of the execution flow.

**3. Input data**

Check whether your processor receives the data it expects:

- Custom Fields
- Line item payload
- System configuration (if used)

If the input is missing, the processor may run but not produce any visible result.

**Keep in mind:** Cart processors work on a runtime cart object, which is recalculated on each request. For most issues, runtime debugging (logs, breakpoints, input data) is the way to go.

## Common Cart Debugging Scenarios

The following scenarios cover some of the most common issues developers encounter when working with cart calculation, validation, and checkout logic.

### Scenario 1: Validation Errors Not Showing

When your custom validator isn't showing error messages, check:

1. **Translation keys**: Ensure your translation files are in the correct location and format
2. **Error level**: Make sure you're using the correct error level (ERROR vs. WARNING)
3. **Blocking behavior**: Verify that `blockOrder()` returns `true` for blocking errors

For our `MinimumOrderValueValidator`, you can debug by adding logging:

```php
public function validate(Cart $cart, ErrorCollection $errors, SalesChannelContext $context): void
{
    $this->logger->info('MinimumOrderValueValidator: Starting validation', [
        'cart_total' => $cart->getPrice()->getTotalPrice(),
        'customer_company' => $context->getCustomer()?->getCompany()
    ]);

    // ... validation logic ...

    if ($total < $minimumValue) {
        $error = new MinimumOrderValueError($total, $minimumValue, $missing);
        $errors->add($error);
        
        $this->logger->warning('MinimumOrderValueValidator: Added error', [
            'error_id' => $error->getId(),
            'current_value' => $total,
            'minimum_value' => $minimumValue
        ]);
    }
}
```

This helps you verify:

- Whether the validator is executed.
- Which values are used during the cart validation.
- Whether the error is actually added to the cart.

### Scenario 2: Performance Issues

If cart loading is slow, use the Symfony profiler to identify bottlenecks:

![Symfony Profiler Performance](assets/symfony-profiler-performance.jpg)

**Focus on the following areas:**

- **Slow database queries** in the Doctrine section.
- **Memory usage** spikes during cart recalculation.
- **Long-running processors** in the cart calculation timeline.

**Typical causes include:**

- Expensive queries inside cart processors.
- Missing cart collectors for shared data.
- Processors running unnecessarily on every recalculation.

### Scenario 3: Cart State Inconsistencies

When cart data seems inconsistent, check the cart calculation phases:

```php
// Debug cart calculation phases
empty($cart->getLineItems()->getElements()); // Check if line items are present. If no items = true.
$cart->getPrice(); // Ensure price calculation exists
```

## Using Console Commands for Cart Debugging

While there's no dedicated `debug:cart` command, you can use several console commands to debug cart-related issues:

```bash
# Check if your custom services are properly registered
bin/console debug:container AcademyCartExamples

# Debug service autowiring for cart processors
bin/console debug:autowiring BulkDiscountProcessor

# Check configuration for cart-related settings
bin/console debug:config | grep -i cart

# Debug event dispatcher to see cart events
bin/console debug:event-dispatcher | grep -i cart
```

**When to use these commands:**

- **`debug:container AcademyCartExamples`** - Verify your custom validators and processors are registered correctly.
- **`debug:autowiring BulkDiscountProcessor`** - Check if your processor can be autowired.
- **`debug:config | grep -i cart`** - Find cart-related configuration settings.
- **`debug:event-dispatcher`** - Useful when debugging event-based extensions that interact with the cart directly.

For most cart debugging, the Symfony profiler's cart sidebar provides the most useful information without needing to dig through console commands.

## Using Xdebug for Cart Inspection

Xdebug provides a powerful way to inspect cart data structures in real-time during development. When you need to understand complex cart state or debug processor logic, Xdebug can be invaluable.

### Setting Breakpoints in Cart Code

Set breakpoints in your cart processors or validators to inspect data:

```php
// In BulkDiscountProcessor.php
public function process(
    CartDataCollection $data,
    Cart $original,
    Cart $toCalculate,
    SalesChannelContext $context,
    CartBehavior $behavior
): void {
    // Set breakpoint here to inspect cart state
    $lineItems = $toCalculate->getLineItems();
    $totalQuantity = $this->calculateTotalQuantity($lineItems);
    
    // Inspect the calculated quantity and discount percentage
    $discountPercentage = $this->getBulkDiscountPercentage($totalQuantity);
    
    if ($discountPercentage > 0) {
        $this->applyBulkDiscount($lineItems, $discountPercentage, $context);
    }
}
```

### Inspecting Cart Data Structures

With Xdebug, you can easily explore:

- **Cart object properties** – Line items, pricing, delivery information.
- **SalesChannelContext** – Customer data, sales channel, currency.
- **LineItem collections** – Individual product data, quantities, prices.
- **Error collections** – Validation errors and their details.

### Quick Data Access

Xdebug's variable inspection gives you instant access to:

- **Cart totals and subtotals** without needing to calculate them.
- **Line item properties** like identifiers, quantities, and pricing.
- **Customer context** including B2B status and company information.
- **Applied discounts and promotions** in real-time.

### Debugging Cart Calculation Flow

Set breakpoints at different stages of cart calculation to understand the flow:

1. **Before processors run** – See the original cart state.
2. **During processor execution** – Inspect data being modified step by step.
3. **After validation** – Check for errors and their impact.
4. **Final cart state** – Verify the calculated result.

This approach is particularly useful when the Symfony profiler doesn't show enough details or when you need to understand the internal state of complex cart operations.

## Best Practices for Cart Debugging

When debugging cart-related issues, the following best practices can help you work efficiently and avoid unnecessary guesswork:

**Always start with the Symfony debug toolbar** – it gives you the quickest overview of what's happening in the cart.

**Use structured logging** – Include relevant context (customer ID, cart token, quantities) in your log messages to make debugging easier.

**Test with different scenarios** – Debug with B2B customers, regular customers, different quantities, and various product types.

**Check service registration** – Ensure your processors and validators are properly registered in `services.xml` with the correct tags and priorities.

**Verify translations** – Cart errors sometimes fail silently due to missing or incorrect translation keys.

## Summary

In this learning unit, you learned:

- How to debug and troubleshoot cart-related issues in Shopware.
- How to use Symfony profiler to inspect the cart state and calculation steps.
- How to add logging to cart processors and validators to understand the execution flow.
- How to identify common issues such as missing validation errors, performance problems, and inconsistent cart states.
- How to use console commands to verify service registration and cart-related configuration.
- How Xdebug can help inspect cart data and follow the cart calculation flow step by step.

With this knowledge, you can systematically analyze cart behavior, locate issues faster, and debug complex checkout logic without confidence.

Effective cart debugging requires a systematic approach: start with the visual tools (Symfony debug toolbar), add logging to understand the flow, and use console commands for detailed inspection. The key is to understand the cart calculation phases and where your custom logic fits into the overall process.

<Callout title="Did You Know?" type="info">

The Symfony debug toolbar's cart sidebar is only available in development mode. In production, you'll need to rely on logging and custom debugging tools to troubleshoot cart issues.

</Callout>
