custom/plugins/WbfkExtensions/src/Subscriber/ProductSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace WbfkExtensions\Subscriber;
  4. use Shopware\Core\Content\Product\ProductEvents;
  5. use Shopware\Core\Framework\Context;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class ProductSubscriber implements EventSubscriberInterface
  11. {
  12.     private EntityRepository $productRepository;
  13.     public function __construct(EntityRepository $productRepository)
  14.     {
  15.         $this->productRepository $productRepository;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             ProductEvents::PRODUCT_WRITTEN_EVENT => 'onProductWrittenEvent',
  21.         ];
  22.     }
  23.     public function onProductWrittenEvent(EntityWrittenEvent $event)
  24.     {
  25.         foreach ($event->getWriteResults() as $entityWriteResult) {
  26.             if ($this->isNewProduct($entityWriteResult)) {
  27.                 $this->setProductNotAvailableForPrivateCustomers($entityWriteResult$event->getContext());
  28.             }
  29.         }
  30.     }
  31.     public function isNewProduct(EntityWriteResult $entityWriteResult): bool
  32.     {
  33.         return $entityWriteResult->getOperation() === EntityWriteResult::OPERATION_INSERT;
  34.     }
  35.     private function setProductNotAvailableForPrivateCustomers(EntityWriteResult $entityWriteResultContext $context): void
  36.     {
  37.         $this->productRepository->update([
  38.             [
  39.                 'id' => $entityWriteResult->getPrimaryKey(),
  40.                 "customFields" => [
  41.                     "wbfk_product_not_for_private" => true,
  42.                 ]
  43.             ]
  44.         ], $context);
  45.     }
  46. }