<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use Shopware\Core\Content\Product\Aggregate\ProductVisibility\ProductVisibilityDefinition;
use Shopware\Core\Content\Product\SalesChannel\ProductAvailableFilter;
use Shopware\Core\Content\ProductExport\Event\ProductExportChangeEncodingEvent;
use Shopware\Core\Content\ProductExport\Event\ProductExportProductCriteriaEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductExportEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
ProductExportChangeEncodingEvent::class => 'onProductExportChangeEncodingEvent',
ProductExportProductCriteriaEvent::class => 'onProductExportProductCriteriaEvent',
];
}
public function onProductExportProductCriteriaEvent(ProductExportProductCriteriaEvent $event): void
{
$criteria = $event->getCriteria();
$criteria->addFilter(new ProductAvailableFilter($event->getSalesChannelContext()->getSalesChannel()->getId(), ProductVisibilityDefinition::VISIBILITY_ALL));
$customFields = $event->getProductExport()->getSalesChannel()->getCustomFields();
if (!empty($customFields['wbfk_feed_delivery_country'])) {
$countryId = $customFields['wbfk_feed_delivery_country'];
$criteria->addAssociation('supplierDeliveryTimes');
$criteria->getAssociation('supplierDeliveryTimes')->addFilter(new EqualsFilter('countryId', $countryId));
}
$criteria->addAssociation('productSuppliers.wbfkSupplier.deliveryTimes');
$productSupplierAssociation = $criteria->getAssociation('productSuppliers');
$productSupplierAssociation->addFilter(new EqualsFilter('active', true));
$productSupplierAssociation->addFilter(new EqualsFilter('wbfkSupplier.isActive', true));
}
public function onProductExportChangeEncodingEvent(ProductExportChangeEncodingEvent $event): void
{
$encodedContent = $event->getEncodedContent();
$productExportEntity = $event->getProductExportEntity();
if ($productExportEntity->getFileFormat() == 'csv') {
$encodedContent = str_replace('>', '>', $encodedContent);
$event->setEncodedContent($encodedContent);
$csvData = str_getcsv($encodedContent, PHP_EOL);
$returnData = [];
foreach ($csvData as $line) {
// skip empty csv lines
if (str_contains($line, '%skipThisLine%')) {
continue;
}
$returnData[] = $line;
}
$returnData = join(PHP_EOL, $returnData);
$event->setEncodedContent($returnData);
}
}
}