<?php declare(strict_types=1);
namespace HbHAlphaplanCustoms\Subscriber;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Product\ProductEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ProductSubscriber implements EventSubscriberInterface
{
public EntityRepository $cvsKProductRepository;
public function __construct(EntityRepository $cvsKProductRepository)
{
$this->cvsKProductRepository = $cvsKProductRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductEvents::PRODUCT_LOADED_EVENT => 'onProductsLoaded',
KernelEvents::REQUEST => 'onKernelRequest'
];
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$controller = $request->attributes->get('_controller');
$params = explode('::',$controller);
if($request->getMethod() === "POST" && stripos($params[0], 'SyncController') !== false){
$content = json_decode($request->getContent(), true);
if(
isset($content[0]['payload'][0]['manufacturerId']) &&
$content[0]['payload'][0]['manufacturerId'] === "0" &&
$content[0]['entity'] === 'product' &&
$content[0]['action'] === 'upsert' &&
$content[0]['key'] === 'write'
){
$content[0]['payload'][0]['manufacturerId'] = null;
$request->initialize(
$request->query->all(),
$request->request->all(),
$request->attributes->all(),
$request->cookies->all(),
$request->files->all(),
$request->server->all(),
json_encode($content)
);
}
}
}
public function onProductsLoaded(EntityLoadedEvent $event): void
{
/** @var ProductEntity $productEntity */
foreach ($event->getEntities() as $productEntity) {
$data = $this->getData($productEntity->getId(), $event->getContext());
if($data !== null){
$productEntity->addExtension('cvs_product_extension', new ArrayEntity(['K_ArzneimittelPflichtText' => $data->getKArzneimittelPflichtText()]));
}
}
}
private function getData($productId, Context $context){
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter("productId", $productId));
$result = $this->cvsKProductRepository->search($criteria, $context);
return $result->getEntities()->first();
}
}