<?php declare(strict_types=1);
namespace WosoExtCrossSellingFeatures\Subscriber;
use Shopware\Core\Content\Product\Events\ProductCrossSellingsLoadedEvent;
use Shopware\Core\Content\Product\Aggregate\ProductCrossSelling\ProductCrossSellingCollection;
use Shopware\Core\Content\Product\Aggregate\ProductCrossSelling\ProductCrossSellingDefinition;
use Shopware\Core\Content\Product\Aggregate\ProductCrossSelling\ProductCrossSellingEntity;
use Shopware\Core\Content\Product\Aggregate\ProductVisibility\ProductVisibilityDefinition;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\System\SystemConfig\SystemConfigService;
class defSubscriber implements EventSubscriberInterface
{
private SystemConfigService $systemConfigService;
public function __construct(SystemConfigService $systemConfigService)
{
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents(): array
{
return [
ProductCrossSellingsLoadedEvent::class => 'onCrossSellingsLoaded'
];
}
public function onCrossSellingsLoaded(ProductCrossSellingsLoadedEvent $event)
{
$config = $this->systemConfigService->get('WosoExtCrossSellingFeatures.config');
if ( (is_null($config)) || (empty($config)) ) { return; }
if ($config['active'] !== true) { return; }
if ( (trim($config['prefixestodelete'])=='') && (trim($config['prefixestohide'])=='') ) { return; }
$prefDelete=[];$prefHide=[];
if ($this->genPrefixArraysByConfig($config, $prefDelete, $prefHide) <= 0) { return; }
$context = $event->getSalesChannelContext();
$results = $event->getCrossSellings();
$results->addExtension('wosoExtCrossSelling', new ArrayEntity(['test'=>'xxx']));
foreach ($results as $csElement) {
$crossSelling = $csElement->getCrossSelling();
$elementname = $crossSelling->getName();
$f='';
foreach ($prefDelete as $n) {
if (strpos($elementname,$n) === 0) {
$f=$n;break;
}
}
if ($f!='') {
$nn = substr($elementname, strlen($f),10000);
$csElement->getCrossSelling()->setName($nn);
$csElement->getCrossSelling()->setTranslated(['name' => $nn]);
}
$f='';
foreach ($prefHide as $n) {
if (strpos($elementname, $n) === 0) {
$f=$n;break;
}
}
if ($f != '') {
$crossSelling->setActive(false);
}
}
}
private function genPrefixArraysByConfig(array $config, array &$prefDelete, array &$prefHide) : int {
$ret = 0;
if (trim($config['prefixestodelete'])!='') {
$x=explode(' ', $config['prefixestodelete']);
foreach ($x as $e) {
$prefDelete[]=$e;
$ret++;
}
}
if (trim($config['prefixestohide'])!='') {
$x=explode(' ', $config['prefixestohide']);
foreach ($x as $e) {
$prefHide[]=$e;
$ret++;
}
}
return $ret;
}
}