src/EventSubscriber/Shop/AddProductToCartAfter/AddFreeAdditions.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Shop\AddProductToCartAfter;
  3. use App\Event\Shop\AddProductToCartAfterEvent;
  4. use App\Shop\ShopManager;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. /**
  7.  * @author Przemysław Chrupek <przemyslaw.chrupek@avt.pl>
  8.  */
  9. class AddFreeAdditions implements EventSubscriberInterface
  10. {
  11.     protected ShopManager $shopManager;
  12.     public function __construct(ShopManager $shopManager)
  13.     {
  14.         $this->shopManager $shopManager;
  15.     }
  16.     public static function getSubscribedEvents()
  17.     {
  18.         return [
  19.             AddProductToCartAfterEvent::NAME => [
  20.                 ['addFreeAdditions'1000],
  21.             ]
  22.         ];
  23.     }
  24.     /**
  25.      * Add free additions to product added to cart
  26.      */
  27.     public function addFreeAdditions(AddProductToCartAfterEvent $event): void
  28.     {
  29.         if (!$this->shouldAddFreeAdditions($event))
  30.             return;
  31.         $product $event->getProduct();
  32.         $productContent $product->getContent();
  33.         $cart $event->getCurrentCart();
  34.         foreach ($product->getContent()->getContents() as $connection) {
  35.             // Check if connected content is addition and is addition to added product
  36.             if (!$this->shopManager->isAdditionToProduct($productContent$connection->getContentConnected()))
  37.                 continue;
  38.             // Check if connected content has products
  39.             if (!$productToAdd $connection->getContentConnected()->getProducts()->first())
  40.                 continue;
  41.             // Check if product exist in cart
  42.             if ($cart->productInCart($productToAdd))
  43.                 continue;
  44.             // Check if product price is 0
  45.             if ($productToAdd->getBasePrice() != 0)
  46.                 continue;
  47.             $cart->addProduct($productToAdd);
  48.         }
  49.     }
  50.     /**
  51.      * Check if conditions are met
  52.      */
  53.     protected function shouldAddFreeAdditions(AddProductToCartAfterEvent $event): bool
  54.     {
  55.         // Check option from settings
  56.         if (!$this->shopManager->addFreeAdditionsWhenProductAddedToCart())
  57.             return false;
  58.         $product $event->getProduct();
  59.         // Check if this is main product
  60.         if (!$this->shopManager->isProduct($product->getContent()))
  61.             return false;
  62.         return true;
  63.     }
  64. }