custom/plugins/WbfkExtensions/src/Subscriber/ActivateOwnStocksOnProductSupplierChanges.php line 28

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace WbfkExtensions\Subscriber;
  4. use Enqueue\MessengerAdapter\EnvelopeItem\TransportConfiguration;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Messenger\MessageBusInterface;
  8. use WbfkExtensions\MessageQueue\Handler\SetOwnWarehouseStocksActiveIfAvailableHandler;
  9. use WbfkExtensions\MessageQueue\Message\SetOwnWarehouseStocksActiveIfAvailable;
  10. class ActivateOwnStocksOnProductSupplierChanges implements EventSubscriberInterface
  11. {
  12. public function __construct(
  13. private readonly MessageBusInterface $bus
  14. ) {
  15. }
  16. public static function getSubscribedEvents(): array
  17. {
  18. return [
  19. 'wbfk_it_scope_product_supplier.written' => 'onProductSupplierWritten',
  20. ];
  21. }
  22. public function onProductSupplierWritten(EntityWrittenEvent $event): void
  23. {
  24. if ($event->getContext()->hasState(
  25. SetOwnWarehouseStocksActiveIfAvailableHandler::OWN_STOCK_ACTIVATION_CONTEXT_STATE
  26. )) {
  27. // Since activation itself leads to 'wbfk_it_scope_product_supplier.written' event,
  28. // We need to skip secondary event else, we will be running activation check multiple times for initial event
  29. return;
  30. }
  31. $changedProductSupplierIds = $this->getChangedProductSupplierIds($event->getPayloads());
  32. if (empty($changedProductSupplierIds)) {
  33. return;
  34. }
  35. $this->bus->dispatch(new SetOwnWarehouseStocksActiveIfAvailable($changedProductSupplierIds), [
  36. new TransportConfiguration([
  37. 'metadata' => [
  38. 'priority' => SetOwnWarehouseStocksActiveIfAvailable::PRIORITY,
  39. ],
  40. ]),
  41. ]);
  42. }
  43. private function getChangedProductSupplierIds(array $payloads): array
  44. {
  45. $changedProductSupplierIds = [];
  46. foreach ($payloads as $payload) {
  47. if (array_key_exists('stock', $payload) || array_key_exists('active', $payload)) {
  48. $changedProductSupplierIds[] = $payload['id'];
  49. }
  50. }
  51. return $changedProductSupplierIds;
  52. }
  53. }