<?php
namespace App\EventSubscriber\Shop\AddProductToCartAfter;
use App\Event\Shop\AddProductToCartAfterEvent;
use App\Shop\ShopManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* @author Przemysław Chrupek <przemyslaw.chrupek@avt.pl>
*/
class AddFreeAdditions implements EventSubscriberInterface
{
protected ShopManager $shopManager;
public function __construct(ShopManager $shopManager)
{
$this->shopManager = $shopManager;
}
public static function getSubscribedEvents()
{
return [
AddProductToCartAfterEvent::NAME => [
['addFreeAdditions', 1000],
]
];
}
/**
* Add free additions to product added to cart
*/
public function addFreeAdditions(AddProductToCartAfterEvent $event): void
{
if (!$this->shouldAddFreeAdditions($event))
return;
$product = $event->getProduct();
$productContent = $product->getContent();
$cart = $event->getCurrentCart();
foreach ($product->getContent()->getContents() as $connection) {
// Check if connected content is addition and is addition to added product
if (!$this->shopManager->isAdditionToProduct($productContent, $connection->getContentConnected()))
continue;
// Check if connected content has products
if (!$productToAdd = $connection->getContentConnected()->getProducts()->first())
continue;
// Check if product exist in cart
if ($cart->productInCart($productToAdd))
continue;
// Check if product price is 0
if ($productToAdd->getBasePrice() != 0)
continue;
$cart->addProduct($productToAdd);
}
}
/**
* Check if conditions are met
*/
protected function shouldAddFreeAdditions(AddProductToCartAfterEvent $event): bool
{
// Check option from settings
if (!$this->shopManager->addFreeAdditionsWhenProductAddedToCart())
return false;
$product = $event->getProduct();
// Check if this is main product
if (!$this->shopManager->isProduct($product->getContent()))
return false;
return true;
}
}