CartExtension example


class CartExtensionTest extends TestCase
{
    /** * This test verifies that we can add a promotion * id and it will be found as "blocked" in the extension * * @group promotions */
    public function testPromotionIsBlocked(): void
    {
        $extension = new CartExtension();
        $extension->blockPromotion('abc');

        static::assertTrue($extension->isPromotionBlocked('abc'));
    }

    /** * This test verifies that a non-existing id * is being returned as "not blocked" * * @group promotions */
    

    public function collect(CartDataCollection $data, Cart $original, SalesChannelContext $context, CartBehavior $behavior): void
    {
        Profiler::trace('cart::promotion::collect', function D) use ($data$original$context$behavior): void {
            // The promotions have a special function:             // If the user comes to the shop via a promotion link, a discount is to be placed in the cart.             // However, this cannot be applied directly, because it does not yet have any items in the cart.             // Therefore the code is stored in the extension and as soon             // as the user has enough items in the cart, it is added again.             $cartExtension = $original->getExtension(CartExtension::KEY);
            if (!$cartExtension instanceof CartExtension) {
                $cartExtension = new CartExtension();
                $original->addExtension(CartExtension::KEY, $cartExtension);
            }

            // if we are in recalculation,             // we must not re-add any promotions. just leave it as it is.             if ($behavior->hasPermission(self::SKIP_PROMOTION)) {
                return;
            }

            // now get the codes from our configuration             // and also from our line items (that already exist)
private function blockPromotion(string $id, Cart $cart): void
    {
        $extension = $this->getExtension($cart);
        $extension->blockPromotion($id);

        $cart->addExtension(CartExtension::KEY, $extension);
    }

    private function getExtension(Cart $cart): CartExtension
    {
        if (!$cart->hasExtension(CartExtension::KEY)) {
            $cart->addExtension(CartExtension::KEY, new CartExtension());
        }

        /** @var CartExtension $extension */
        $extension = $cart->getExtension(CartExtension::KEY);

        return $extension;
    }
}
Home | Imprint | This part of the site doesn't use cookies.