<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
private EntityRepository $productRepository;
public function __construct(EntityRepository $productRepository)
{
$this->productRepository = $productRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductEvents::PRODUCT_WRITTEN_EVENT => 'onProductWrittenEvent',
];
}
public function onProductWrittenEvent(EntityWrittenEvent $event)
{
foreach ($event->getWriteResults() as $entityWriteResult) {
if ($this->isNewProduct($entityWriteResult)) {
$this->setProductNotAvailableForPrivateCustomers($entityWriteResult, $event->getContext());
}
}
}
public function isNewProduct(EntityWriteResult $entityWriteResult): bool
{
return $entityWriteResult->getOperation() === EntityWriteResult::OPERATION_INSERT;
}
private function setProductNotAvailableForPrivateCustomers(EntityWriteResult $entityWriteResult, Context $context): void
{
$this->productRepository->update([
[
'id' => $entityWriteResult->getPrimaryKey(),
"customFields" => [
"wbfk_product_not_for_private" => true,
]
]
], $context);
}
}