addErrors example

public function testAddPromotion(): void
    {
        $code = Uuid::randomHex();

        $request = new Request([]['code' => $code]);
        $cart = new Cart(Uuid::randomHex());
        $context = $this->createMock(SalesChannelContext::class);
        $uniqueKey = PromotionItemBuilder::PLACEHOLDER_PREFIX . $code;
        $item = new LineItem($uniqueKey, PromotionProcessor::LINE_ITEM_TYPE);
        $item->setLabel($code);
        $cart->addErrors(new PromotionCartAddedInformationError($item));

        $this->promotionItemBuilderMock->method('buildPlaceholderItem')->willReturn($item);

        $this->cartService->expects(static::once())
            ->method('add')
            ->with($cart$item$context)
            ->willReturn($cart);

        $this->translatorCallback();

        $this->controller->addPromotion($cart$request$context);
    }
use Shopware\Core\Framework\Log\Package;

#[Package('buyers-experience')] trait PromotionCartInformationTrait
{
    /** * Adds a new error to the cart if the promotion for * the provided code was not found as active and valid promotion. */
    private function addPromotionNotFoundError(string $code, Cart $cart): void
    {
        $cart->addErrors(new PromotionNotFoundError($code));
    }

    /** * Adds a new error to the cart if the promotion has been found * but somehow is not eligible for the current cart. */
    private function addPromotionNotEligibleError(string $name, Cart $cart): void
    {
        $cart->addErrors(new PromotionNotEligibleError($name));
    }

    


            // if promotion is on exclusions stack it is ignored             if (!$discountItem->hasPayloadValue('promotionId')) {
                continue;
            }

            $promotionId = $discountItem->getPayloadValue('promotionId');

            if (\array_key_exists($promotionId$exclusions)) {
                if (!$isAutomaticDiscount) {
                    $calculated->addErrors(new PromotionExcludedError($discountItem->getDescription() ?? $discountItem->getId()));
                }

                continue;
            }

            $result = $this->calculateDiscount($discountItem$calculated$context);

            // if our price is 0,00 because of whatever reason, make sure to skip it.             // this can be if the price-definition filter is none,             // or if a fixed price is set to the price of the product itself.             if (abs($result->getPrice()->getTotalPrice()) === 0.0) {
                


        $guestCart = $this->cartService->getCart($token$currentContext);
        $customerCart = $this->cartService->getCart($customerContext->getToken()$customerContext);

        if ($guestCart->getLineItems()->count() > 0) {
            $restoredCart = $this->mergeCart($customerCart$guestCart$customerContext);
        } else {
            $restoredCart = $this->cartService->recalculate($customerCart$customerContext);
        }

        $restoredCart->addErrors(...array_values($guestCart->getErrors()->getPersistent()->getElements()));

        $this->deleteGuestContext($currentContext$customerId);

        $errors = $restoredCart->getErrors();
        $result = $this->cartRuleLoader->loadByToken($customerContext$restoredCart->getToken());

        $cartWithErrors = $result->getCart();
        $cartWithErrors->setErrors($errors);
        $this->cartService->setCart($cartWithErrors);

        $this->eventDispatcher->dispatch(new SalesChannelContextRestoredEvent($customerContext$currentContext));

        

        $error = new GenericCartError(
            'generic_test_error',
            'test.error.message',
            ['test' => 'error'],
            Error::LEVEL_ERROR,
            true,
            true
        );

        $cart = new Cart('foo');
        $cart->addErrors($error);

        $request = new Request();
        $session = new Session(new TestSessionStorage());

        $request->setSession($session);

        $stack = new RequestStack();
        $stack->push($request);

        $translator = static::createMock(TranslatorInterface::class);
        $translator
            
// move data from previous calculation into new cart             $cart->setData($original->getData());

            $this->runProcessors($original$cart$context$behavior);

            if ($behavior->hookAware()) {
                $this->executor->execute(new CartHook($cart$context));
            }

            $this->calculateAmount($context$cart);

            $cart->addErrors(
                ...$this->validator->validate($cart$context)
            );

            $cart->setTransactions(
                $this->transactionProcessor->process($cart$context)
            );

            $cart->setRuleIds($context->getRuleIds());

            return $cart;
        }, 'cart');
    }
continue;
            }

            // if promotion is on exclusions stack it is ignored             if (!$discountItem->hasPayloadValue('promotionId')) {
                continue;
            }

            $promotionId = $discountItem->getPayloadValue('promotionId');

            if (\array_key_exists($promotionId$exclusions)) {
                $toCalculate->addErrors(new PromotionNotEligibleError($discountItem->getDescription() ?? $discountItem->getId()));

                continue;
            }

            $deliveryItemAdded = $this->calculateDeliveryPromotion($toCalculate$discountItem$context$notDiscountedDeliveriesValue);

            if ($deliveryItemAdded) {
                // ensure that a lineItem will be added to cart if a discount has been added                 $this->addFakeLineitem($toCalculate$discountItem$context);
                $this->addPromotionAddedNotice($original$toCalculate$discountItem);
            } else {
                
$minPurchase = $quantityInformation->getMinPurchase();
            $available = $quantityInformation->getMaxPurchase() ?? 0;
            $steps = $quantityInformation->getPurchaseSteps() ?? 1;

            if ($available >= $quantity) {
                continue;
            }

            $maxAvailable = (int) (floor(($available - $minPurchase) / $steps) * $steps + $minPurchase);

            $cart->addErrors(
                new ProductStockReachedError($productId(string) $lineItem->getLabel()$maxAvailable, false),
            );
        }
    }
}
$toCalculate->add($item);
                }

                return;
            }

            // if there is no collected promotion we may return - nothing to calculate!             if (!$data->has(self::DATA_KEY)) {
                $lineItemPromotions = $original->getLineItems()->filterType(self::LINE_ITEM_TYPE);
                foreach ($lineItemPromotions as $lineItemPromotion) {
                    if (empty($lineItemPromotion->getReferencedId())) {
                        $toCalculate->addErrors(
                            new AutoPromotionNotFoundError($lineItemPromotion->getLabel() ?? $lineItemPromotion->getId())
                        );
                    }
                }

                return;
            }

            /** @var LineItemCollection $discountLineItems */
            $discountLineItems = $data->get(self::DATA_KEY);

            

        }

        // Fetch default price if no rule matched         if ($costs === null) {
            /** @var ShippingMethodPriceCollection $shippingPrices */
            $shippingPrices = $shippingMethod->getPrices()->filterByProperty('ruleId', null);
            $costs = $this->getMatchingPriceOfRule($delivery$context$shippingPrices);
        }

        if (!$costs) {
            $cart->addErrors(
                new ShippingMethodBlockedError((string) $shippingMethod->getTranslation('name'))
            );

            return;
        }

        $delivery->setShippingCosts($costs);
    }

    private function hasDeliveryWithOnlyShippingFreeItems(Delivery $delivery): bool
    {
        


        // product data was never detected and the product is not inside the data collection         if ($product !== null || $item->getDataTimestamp() !== null) {
            return;
        }

        if ($behavior->hasPermission(self::KEEP_INACTIVE_PRODUCT)) {
            return;
        }

        $cart->addErrors(new ProductNotFoundError($item->getLabel() ?: $item->getId()));

        $items->remove($item->getId());
    }

    private function validateParents(LineItem $item, CartDataCollection $data, LineItemCollection $items): void
    {
        $product = $data->get(
            $this->getDataKey((string) $item->getReferencedId())
        );

        // no data for enrich exists
$items = $original->getLineItems()->filterType(LineItem::DISCOUNT_LINE_ITEM);

        $goods = $toCalculate->getLineItems()->filterGoods();

        foreach ($items as $item) {
            $definition = $item->getPriceDefinition();

            try {
                $price = $this->calculate($definition$goods$context);
            } catch (CartException) {
                $original->remove($item->getId());
                $toCalculate->addErrors(new IncompleteLineItemError($item->getId(), 'price'));

                continue;
            }

            if (!$this->validate($price$goods$toCalculate)) {
                $original->remove($item->getId());

                continue;
            }

            $item->setPrice($price);

            
$calculatedTaxForProductItem = array_filter($shippingCalculatedTaxesfn (CalculatedTax $tax) => (int) $tax->getTaxRate() === $taxForProductItem);

        static::assertNotEmpty($calculatedTaxForProductItem);
        static::assertCount(1, $calculatedTaxForProductItem);
    }

    public function testPersistentErrors(): void
    {
        $cart = new Cart(Uuid::randomHex());

        $cart->addErrors(new NonePersistentError()new PersistentError());

        $cart = $this->getContainer()->get(Processor::class)
            ->process($cart$this->context, new CartBehavior());

        static::assertCount(1, $cart->getErrors());
        static::assertInstanceOf(PersistentError::class$cart->getErrors()->first());

        $error = $cart->getErrors()->first();
        static::assertEquals('persistent', $error->getId());
        static::assertEquals('persistent', $error->getMessageKey());
    }

    
$request = new Request();
        $request->query->set('redirected', true);

        $response = $this->controller->cartPage($request$this->createMock(SalesChannelContext::class));

        static::assertEquals(new Response()$response);
    }

    public function testGetCartRedirectOnShippingErrors(): void
    {
        $cart = new Cart(Uuid::randomHex());
        $cart->addErrors(new ShippingMethodChangedError('old', 'new'));

        $cartPage = new CheckoutCartPage();
        $cartPage->setCart($cart);

        $this->cartPageLoaderMock->method('load')->willReturn(
            $cartPage
        );

        $request = new Request();
        $request->query->set('redirected', false);

        
/** * @param AbstractManifestValidator[] $validators */
    public function __construct(private readonly iterable $validators)
    {
    }

    public function validate(Manifest $manifest, Context $context): void
    {
        $errors = new ErrorCollection();
        foreach ($this->validators as $validator) {
            $errors->addErrors($validator->validate($manifest$context));
        }

        if ($errors->count() === 0) {
            return;
        }

        throw new AppValidationException($manifest->getMetadata()->getName()$errors);
    }
}
Home | Imprint | This part of the site doesn't use cookies.