<?php
declare(strict_types=1);
namespace NetInventors\NetiNextEasyCouponDesigns\Core\Checkout\Cart\ValidateSelectedDesign;
use NetInventors\NetiNextEasyCouponDesigns\Struct\LineItemStruct;
use NetInventors\NetiNextEasyCouponDesigns\Struct\PluginConfigStruct;
use NetInventors\NetiNextEasyCouponDesigns\Struct\SelectedDesignCollection;
use Shopware\Core\Checkout\Cart\Cart;
use Shopware\Core\Checkout\Cart\CartBehavior;
use Shopware\Core\Checkout\Cart\CartDataCollectorInterface;
use Shopware\Core\Checkout\Cart\LineItem\CartDataCollection;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
class CartCollector extends AbstractCartValidator implements CartDataCollectorInterface
{
public const CACHE_KEY = 'easy-coupon-designs-products-with-selected-designs';
protected PluginConfigStruct $pluginConfig;
protected EntityRepositoryInterface $designRepository;
public function __construct(PluginConfigStruct $pluginConfig, EntityRepositoryInterface $designRepository)
{
$this->pluginConfig = $pluginConfig;
$this->designRepository = $designRepository;
}
public function collect(
CartDataCollection $data,
Cart $original,
SalesChannelContext $context,
CartBehavior $behavior
): void {
if (!$this->pluginConfig->isActive()) {
return;
}
$selected = new SelectedDesignCollection();
$products = $original->getLineItems()->filterType(LineItem::PRODUCT_LINE_ITEM_TYPE);
foreach ($products as $product) {
if (!$product->hasPayloadValue(LineItemStruct::PAYLOAD_NAME)) {
continue;
}
$designsSettings = $product->getPayloadValue(LineItemStruct::PAYLOAD_NAME);
if (
isset($designsSettings['selectedDesign'])
&& (
!\is_string($designsSettings['selectedDesign'])
|| '' === $designsSettings['selectedDesign']
)
) {
continue;
}
if (!isset($designsSettings['selectedDesign']) || !Uuid::isValid($designsSettings['selectedDesign'])) {
$this->handleNotExistingDesign($original, $original, $product->getId());
continue;
}
$selected->set($product->getId(), $designsSettings['selectedDesign']);
}
$selectedIds = $selected->getElements();
$designs = $this->designRepository->search(
new Criteria(\array_values($selectedIds)),
$context->getContext()
);
$data->set(self::CACHE_KEY, $designs);
}
}